From 62dcfcd867c54753a608830cabfbfa3a7907c9a5 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 22 Mar 2023 20:03:55 +0000 Subject: [PATCH] docs: Fix formatting of request arg in docstring chore: Update gapic-generator-python to v1.9.1 PiperOrigin-RevId: 518604533 Source-Link: https://github.com/googleapis/googleapis/commit/8a085aeddfa010af5bcef090827aac5255383d7e Source-Link: https://github.com/googleapis/googleapis-gen/commit/b2ab4b0a0ae2907e812c209198a74e0898afcb04 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjJhYjRiMGEwYWUyOTA3ZTgxMmMyMDkxOThhNzRlMDg5OGFmY2IwNCJ9 --- owl-bot-staging/v1beta1/.coveragerc | 13 + owl-bot-staging/v1beta1/.flake8 | 33 + owl-bot-staging/v1beta1/MANIFEST.in | 2 + owl-bot-staging/v1beta1/README.rst | 49 + owl-bot-staging/v1beta1/docs/conf.py | 376 ++ owl-bot-staging/v1beta1/docs/index.rst | 7 + .../catalog_service.rst | 10 + .../prediction_api_key_registry.rst | 10 + .../prediction_service.rst | 10 + .../recommendationengine_v1beta1/services.rst | 9 + .../recommendationengine_v1beta1/types.rst | 6 + .../user_event_service.rst | 10 + .../cloud/recommendationengine/__init__.py | 121 + .../recommendationengine/gapic_version.py | 16 + .../cloud/recommendationengine/py.typed | 2 + .../recommendationengine_v1beta1/__init__.py | 122 + .../gapic_metadata.json | 310 ++ .../gapic_version.py | 16 + .../recommendationengine_v1beta1/py.typed | 2 + .../services/__init__.py | 15 + .../services/catalog_service/__init__.py | 22 + .../services/catalog_service/async_client.py | 966 ++++ .../services/catalog_service/client.py | 1137 +++++ .../services/catalog_service/pagers.py | 140 + .../catalog_service/transports/__init__.py | 38 + .../catalog_service/transports/base.py | 270 + .../catalog_service/transports/grpc.py | 424 ++ .../transports/grpc_asyncio.py | 423 ++ .../catalog_service/transports/rest.py | 907 ++++ .../prediction_api_key_registry/__init__.py | 22 + .../async_client.py | 541 ++ .../prediction_api_key_registry/client.py | 733 +++ .../prediction_api_key_registry/pagers.py | 139 + .../transports/__init__.py | 38 + .../transports/base.py | 198 + .../transports/grpc.py | 326 ++ .../transports/grpc_asyncio.py | 325 ++ .../transports/rest.py | 507 ++ .../services/prediction_service/__init__.py | 22 + .../prediction_service/async_client.py | 377 ++ .../services/prediction_service/client.py | 574 +++ .../services/prediction_service/pagers.py | 139 + .../prediction_service/transports/__init__.py | 38 + .../prediction_service/transports/base.py | 155 + .../prediction_service/transports/grpc.py | 268 + .../transports/grpc_asyncio.py | 267 + .../prediction_service/transports/rest.py | 297 ++ .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 1029 ++++ .../services/user_event_service/client.py | 1198 +++++ .../services/user_event_service/pagers.py | 140 + .../user_event_service/transports/__init__.py | 38 + .../user_event_service/transports/base.py | 249 + .../user_event_service/transports/grpc.py | 407 ++ .../transports/grpc_asyncio.py | 406 ++ .../user_event_service/transports/rest.py | 869 ++++ .../types/__init__.py | 116 + .../types/catalog.py | 349 ++ .../types/catalog_service.py | 187 + .../types/common.py | 97 + .../types/import_.py | 398 ++ .../prediction_apikey_registry_service.py | 146 + .../types/prediction_service.py | 277 + .../types/recommendationengine_resources.py | 26 + .../types/user_event.py | 536 ++ .../types/user_event_service.py | 298 ++ owl-bot-staging/v1beta1/mypy.ini | 3 + owl-bot-staging/v1beta1/noxfile.py | 184 + ...talog_service_create_catalog_item_async.py | 58 + ...atalog_service_create_catalog_item_sync.py | 58 + ...talog_service_delete_catalog_item_async.py | 50 + ...atalog_service_delete_catalog_item_sync.py | 50 + ..._catalog_service_get_catalog_item_async.py | 52 + ...d_catalog_service_get_catalog_item_sync.py | 52 + ...alog_service_import_catalog_items_async.py | 56 + ...talog_service_import_catalog_items_sync.py | 56 + ...atalog_service_list_catalog_items_async.py | 53 + ...catalog_service_list_catalog_items_sync.py | 53 + ...talog_service_update_catalog_item_async.py | 58 + ...atalog_service_update_catalog_item_sync.py | 58 + ...e_prediction_api_key_registration_async.py | 52 + ...te_prediction_api_key_registration_sync.py | 52 + ...e_prediction_api_key_registration_async.py | 50 + ...te_prediction_api_key_registration_sync.py | 50 + ..._prediction_api_key_registrations_async.py | 53 + ...t_prediction_api_key_registrations_sync.py | 53 + ...erated_prediction_service_predict_async.py | 58 + ...nerated_prediction_service_predict_sync.py | 58 + ..._event_service_collect_user_event_async.py | 53 + ...r_event_service_collect_user_event_sync.py | 53 + ..._event_service_import_user_events_async.py | 56 + ...r_event_service_import_user_events_sync.py | 56 + ...er_event_service_list_user_events_async.py | 53 + ...ser_event_service_list_user_events_sync.py | 53 + ...r_event_service_purge_user_events_async.py | 57 + ...er_event_service_purge_user_events_sync.py | 57 + ...er_event_service_write_user_event_async.py | 57 + ...ser_event_service_write_user_event_sync.py | 57 + ...le.cloud.recommendationengine.v1beta1.json | 2570 ++++++++++ ...p_recommendationengine_v1beta1_keywords.py | 190 + owl-bot-staging/v1beta1/setup.py | 90 + .../v1beta1/testing/constraints-3.10.txt | 6 + .../v1beta1/testing/constraints-3.11.txt | 6 + .../v1beta1/testing/constraints-3.12.txt | 6 + .../v1beta1/testing/constraints-3.7.txt | 9 + .../v1beta1/testing/constraints-3.8.txt | 6 + .../v1beta1/testing/constraints-3.9.txt | 6 + owl-bot-staging/v1beta1/tests/__init__.py | 16 + .../v1beta1/tests/unit/__init__.py | 16 + .../v1beta1/tests/unit/gapic/__init__.py | 16 + .../recommendationengine_v1beta1/__init__.py | 16 + .../test_catalog_service.py | 4526 +++++++++++++++++ .../test_prediction_api_key_registry.py | 2888 +++++++++++ .../test_prediction_service.py | 1967 +++++++ .../test_user_event_service.py | 4013 +++++++++++++++ 115 files changed, 35386 insertions(+) create mode 100644 owl-bot-staging/v1beta1/.coveragerc create mode 100644 owl-bot-staging/v1beta1/.flake8 create mode 100644 owl-bot-staging/v1beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1beta1/README.rst create mode 100644 owl-bot-staging/v1beta1/docs/conf.py create mode 100644 owl-bot-staging/v1beta1/docs/index.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst create mode 100644 owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine/gapic_version.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_version.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/rest.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/rest.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/rest.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/rest.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py create mode 100644 owl-bot-staging/v1beta1/mypy.ini create mode 100644 owl-bot-staging/v1beta1/noxfile.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.recommendationengine.v1beta1.json create mode 100644 owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py create mode 100644 owl-bot-staging/v1beta1/setup.py create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1beta1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc new file mode 100644 index 00000000..2de92f85 --- /dev/null +++ b/owl-bot-staging/v1beta1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/recommendationengine/__init__.py + google/cloud/recommendationengine/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/v1beta1/.flake8 b/owl-bot-staging/v1beta1/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v1beta1/.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/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in new file mode 100644 index 00000000..5054f413 --- /dev/null +++ b/owl-bot-staging/v1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/recommendationengine *.py +recursive-include google/cloud/recommendationengine_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst new file mode 100644 index 00000000..11130784 --- /dev/null +++ b/owl-bot-staging/v1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Recommendationengine 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 Recommendationengine 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/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py new file mode 100644 index 00000000..a3730a65 --- /dev/null +++ b/owl-bot-staging/v1beta1/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-recommendations-ai 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-recommendations-ai" +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-recommendations-ai-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-recommendations-ai.tex", + u"google-cloud-recommendations-ai 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-recommendations-ai", + u"Google Cloud Recommendationengine 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-recommendations-ai", + u"google-cloud-recommendations-ai Documentation", + author, + "google-cloud-recommendations-ai", + "GAPIC library for Google Cloud Recommendationengine 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/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst new file mode 100644 index 00000000..b7e1db6b --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + recommendationengine_v1beta1/services + recommendationengine_v1beta1/types diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst new file mode 100644 index 00000000..48f7c814 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/catalog_service.rst @@ -0,0 +1,10 @@ +CatalogService +-------------------------------- + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.catalog_service + :members: + :inherited-members: + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst new file mode 100644 index 00000000..74874c31 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst @@ -0,0 +1,10 @@ +PredictionApiKeyRegistry +------------------------------------------ + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry + :members: + :inherited-members: + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst new file mode 100644 index 00000000..7d2fc56d --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/prediction_service.rst @@ -0,0 +1,10 @@ +PredictionService +----------------------------------- + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_service + :members: + :inherited-members: + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst new file mode 100644 index 00000000..ced8732d --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/services.rst @@ -0,0 +1,9 @@ +Services for Google Cloud Recommendationengine v1beta1 API +========================================================== +.. toctree:: + :maxdepth: 2 + + catalog_service + prediction_api_key_registry + prediction_service + user_event_service diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst new file mode 100644 index 00000000..327866dd --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Recommendationengine v1beta1 API +======================================================= + +.. automodule:: google.cloud.recommendationengine_v1beta1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst new file mode 100644 index 00000000..728ec7e9 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/recommendationengine_v1beta1/user_event_service.rst @@ -0,0 +1,10 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.user_event_service + :members: + :inherited-members: + +.. automodule:: google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py new file mode 100644 index 00000000..ebbf94e4 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/__init__.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.recommendationengine import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.recommendationengine_v1beta1.services.catalog_service.client import CatalogServiceClient +from google.cloud.recommendationengine_v1beta1.services.catalog_service.async_client import CatalogServiceAsyncClient +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.client import PredictionApiKeyRegistryClient +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.async_client import PredictionApiKeyRegistryAsyncClient +from google.cloud.recommendationengine_v1beta1.services.prediction_service.client import PredictionServiceClient +from google.cloud.recommendationengine_v1beta1.services.prediction_service.async_client import PredictionServiceAsyncClient +from google.cloud.recommendationengine_v1beta1.services.user_event_service.client import UserEventServiceClient +from google.cloud.recommendationengine_v1beta1.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.recommendationengine_v1beta1.types.catalog import CatalogItem +from google.cloud.recommendationengine_v1beta1.types.catalog import Image +from google.cloud.recommendationengine_v1beta1.types.catalog import ProductCatalogItem +from google.cloud.recommendationengine_v1beta1.types.catalog_service import CreateCatalogItemRequest +from google.cloud.recommendationengine_v1beta1.types.catalog_service import DeleteCatalogItemRequest +from google.cloud.recommendationengine_v1beta1.types.catalog_service import GetCatalogItemRequest +from google.cloud.recommendationengine_v1beta1.types.catalog_service import ListCatalogItemsRequest +from google.cloud.recommendationengine_v1beta1.types.catalog_service import ListCatalogItemsResponse +from google.cloud.recommendationengine_v1beta1.types.catalog_service import UpdateCatalogItemRequest +from google.cloud.recommendationengine_v1beta1.types.common import FeatureMap +from google.cloud.recommendationengine_v1beta1.types.import_ import CatalogInlineSource +from google.cloud.recommendationengine_v1beta1.types.import_ import GcsSource +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportCatalogItemsRequest +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportCatalogItemsResponse +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportErrorsConfig +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportMetadata +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportUserEventsRequest +from google.cloud.recommendationengine_v1beta1.types.import_ import ImportUserEventsResponse +from google.cloud.recommendationengine_v1beta1.types.import_ import InputConfig +from google.cloud.recommendationengine_v1beta1.types.import_ import UserEventImportSummary +from google.cloud.recommendationengine_v1beta1.types.import_ import UserEventInlineSource +from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import CreatePredictionApiKeyRegistrationRequest +from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import DeletePredictionApiKeyRegistrationRequest +from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsRequest +from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsResponse +from google.cloud.recommendationengine_v1beta1.types.prediction_apikey_registry_service import PredictionApiKeyRegistration +from google.cloud.recommendationengine_v1beta1.types.prediction_service import PredictRequest +from google.cloud.recommendationengine_v1beta1.types.prediction_service import PredictResponse +from google.cloud.recommendationengine_v1beta1.types.user_event import EventDetail +from google.cloud.recommendationengine_v1beta1.types.user_event import ProductDetail +from google.cloud.recommendationengine_v1beta1.types.user_event import ProductEventDetail +from google.cloud.recommendationengine_v1beta1.types.user_event import PurchaseTransaction +from google.cloud.recommendationengine_v1beta1.types.user_event import UserEvent +from google.cloud.recommendationengine_v1beta1.types.user_event import UserInfo +from google.cloud.recommendationengine_v1beta1.types.user_event_service import CollectUserEventRequest +from google.cloud.recommendationengine_v1beta1.types.user_event_service import ListUserEventsRequest +from google.cloud.recommendationengine_v1beta1.types.user_event_service import ListUserEventsResponse +from google.cloud.recommendationengine_v1beta1.types.user_event_service import PurgeUserEventsMetadata +from google.cloud.recommendationengine_v1beta1.types.user_event_service import PurgeUserEventsRequest +from google.cloud.recommendationengine_v1beta1.types.user_event_service import PurgeUserEventsResponse +from google.cloud.recommendationengine_v1beta1.types.user_event_service import WriteUserEventRequest + +__all__ = ('CatalogServiceClient', + 'CatalogServiceAsyncClient', + 'PredictionApiKeyRegistryClient', + 'PredictionApiKeyRegistryAsyncClient', + 'PredictionServiceClient', + 'PredictionServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'CatalogItem', + 'Image', + 'ProductCatalogItem', + 'CreateCatalogItemRequest', + 'DeleteCatalogItemRequest', + 'GetCatalogItemRequest', + 'ListCatalogItemsRequest', + 'ListCatalogItemsResponse', + 'UpdateCatalogItemRequest', + 'FeatureMap', + 'CatalogInlineSource', + 'GcsSource', + 'ImportCatalogItemsRequest', + 'ImportCatalogItemsResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'InputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'CreatePredictionApiKeyRegistrationRequest', + 'DeletePredictionApiKeyRegistrationRequest', + 'ListPredictionApiKeyRegistrationsRequest', + 'ListPredictionApiKeyRegistrationsResponse', + 'PredictionApiKeyRegistration', + 'PredictRequest', + 'PredictResponse', + 'EventDetail', + 'ProductDetail', + 'ProductEventDetail', + 'PurchaseTransaction', + 'UserEvent', + 'UserInfo', + 'CollectUserEventRequest', + 'ListUserEventsRequest', + 'ListUserEventsResponse', + 'PurgeUserEventsMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine/gapic_version.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/gapic_version.py new file mode 100644 index 00000000..405b1ceb --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/gapic_version.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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed new file mode 100644 index 00000000..41689a36 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-recommendations-ai package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py new file mode 100644 index 00000000..c483c891 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/__init__.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.recommendationengine_v1beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.catalog_service import CatalogServiceClient +from .services.catalog_service import CatalogServiceAsyncClient +from .services.prediction_api_key_registry import PredictionApiKeyRegistryClient +from .services.prediction_api_key_registry import PredictionApiKeyRegistryAsyncClient +from .services.prediction_service import PredictionServiceClient +from .services.prediction_service import PredictionServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.catalog import CatalogItem +from .types.catalog import Image +from .types.catalog import ProductCatalogItem +from .types.catalog_service import CreateCatalogItemRequest +from .types.catalog_service import DeleteCatalogItemRequest +from .types.catalog_service import GetCatalogItemRequest +from .types.catalog_service import ListCatalogItemsRequest +from .types.catalog_service import ListCatalogItemsResponse +from .types.catalog_service import UpdateCatalogItemRequest +from .types.common import FeatureMap +from .types.import_ import CatalogInlineSource +from .types.import_ import GcsSource +from .types.import_ import ImportCatalogItemsRequest +from .types.import_ import ImportCatalogItemsResponse +from .types.import_ import ImportErrorsConfig +from .types.import_ import ImportMetadata +from .types.import_ import ImportUserEventsRequest +from .types.import_ import ImportUserEventsResponse +from .types.import_ import InputConfig +from .types.import_ import UserEventImportSummary +from .types.import_ import UserEventInlineSource +from .types.prediction_apikey_registry_service import CreatePredictionApiKeyRegistrationRequest +from .types.prediction_apikey_registry_service import DeletePredictionApiKeyRegistrationRequest +from .types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsRequest +from .types.prediction_apikey_registry_service import ListPredictionApiKeyRegistrationsResponse +from .types.prediction_apikey_registry_service import PredictionApiKeyRegistration +from .types.prediction_service import PredictRequest +from .types.prediction_service import PredictResponse +from .types.user_event import EventDetail +from .types.user_event import ProductDetail +from .types.user_event import ProductEventDetail +from .types.user_event import PurchaseTransaction +from .types.user_event import UserEvent +from .types.user_event import UserInfo +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import ListUserEventsRequest +from .types.user_event_service import ListUserEventsResponse +from .types.user_event_service import PurgeUserEventsMetadata +from .types.user_event_service import PurgeUserEventsRequest +from .types.user_event_service import PurgeUserEventsResponse +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CatalogServiceAsyncClient', + 'PredictionApiKeyRegistryAsyncClient', + 'PredictionServiceAsyncClient', + 'UserEventServiceAsyncClient', +'CatalogInlineSource', +'CatalogItem', +'CatalogServiceClient', +'CollectUserEventRequest', +'CreateCatalogItemRequest', +'CreatePredictionApiKeyRegistrationRequest', +'DeleteCatalogItemRequest', +'DeletePredictionApiKeyRegistrationRequest', +'EventDetail', +'FeatureMap', +'GcsSource', +'GetCatalogItemRequest', +'Image', +'ImportCatalogItemsRequest', +'ImportCatalogItemsResponse', +'ImportErrorsConfig', +'ImportMetadata', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'InputConfig', +'ListCatalogItemsRequest', +'ListCatalogItemsResponse', +'ListPredictionApiKeyRegistrationsRequest', +'ListPredictionApiKeyRegistrationsResponse', +'ListUserEventsRequest', +'ListUserEventsResponse', +'PredictRequest', +'PredictResponse', +'PredictionApiKeyRegistration', +'PredictionApiKeyRegistryClient', +'PredictionServiceClient', +'ProductCatalogItem', +'ProductDetail', +'ProductEventDetail', +'PurchaseTransaction', +'PurgeUserEventsMetadata', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'UpdateCatalogItemRequest', +'UserEvent', +'UserEventImportSummary', +'UserEventInlineSource', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json new file mode 100644 index 00000000..63ee770d --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_metadata.json @@ -0,0 +1,310 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.recommendationengine_v1beta1", + "protoPackage": "google.cloud.recommendationengine.v1beta1", + "schema": "1.0", + "services": { + "CatalogService": { + "clients": { + "grpc": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "CreateCatalogItem": { + "methods": [ + "create_catalog_item" + ] + }, + "DeleteCatalogItem": { + "methods": [ + "delete_catalog_item" + ] + }, + "GetCatalogItem": { + "methods": [ + "get_catalog_item" + ] + }, + "ImportCatalogItems": { + "methods": [ + "import_catalog_items" + ] + }, + "ListCatalogItems": { + "methods": [ + "list_catalog_items" + ] + }, + "UpdateCatalogItem": { + "methods": [ + "update_catalog_item" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CatalogServiceAsyncClient", + "rpcs": { + "CreateCatalogItem": { + "methods": [ + "create_catalog_item" + ] + }, + "DeleteCatalogItem": { + "methods": [ + "delete_catalog_item" + ] + }, + "GetCatalogItem": { + "methods": [ + "get_catalog_item" + ] + }, + "ImportCatalogItems": { + "methods": [ + "import_catalog_items" + ] + }, + "ListCatalogItems": { + "methods": [ + "list_catalog_items" + ] + }, + "UpdateCatalogItem": { + "methods": [ + "update_catalog_item" + ] + } + } + }, + "rest": { + "libraryClient": "CatalogServiceClient", + "rpcs": { + "CreateCatalogItem": { + "methods": [ + "create_catalog_item" + ] + }, + "DeleteCatalogItem": { + "methods": [ + "delete_catalog_item" + ] + }, + "GetCatalogItem": { + "methods": [ + "get_catalog_item" + ] + }, + "ImportCatalogItems": { + "methods": [ + "import_catalog_items" + ] + }, + "ListCatalogItems": { + "methods": [ + "list_catalog_items" + ] + }, + "UpdateCatalogItem": { + "methods": [ + "update_catalog_item" + ] + } + } + } + } + }, + "PredictionApiKeyRegistry": { + "clients": { + "grpc": { + "libraryClient": "PredictionApiKeyRegistryClient", + "rpcs": { + "CreatePredictionApiKeyRegistration": { + "methods": [ + "create_prediction_api_key_registration" + ] + }, + "DeletePredictionApiKeyRegistration": { + "methods": [ + "delete_prediction_api_key_registration" + ] + }, + "ListPredictionApiKeyRegistrations": { + "methods": [ + "list_prediction_api_key_registrations" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionApiKeyRegistryAsyncClient", + "rpcs": { + "CreatePredictionApiKeyRegistration": { + "methods": [ + "create_prediction_api_key_registration" + ] + }, + "DeletePredictionApiKeyRegistration": { + "methods": [ + "delete_prediction_api_key_registration" + ] + }, + "ListPredictionApiKeyRegistrations": { + "methods": [ + "list_prediction_api_key_registrations" + ] + } + } + }, + "rest": { + "libraryClient": "PredictionApiKeyRegistryClient", + "rpcs": { + "CreatePredictionApiKeyRegistration": { + "methods": [ + "create_prediction_api_key_registration" + ] + }, + "DeletePredictionApiKeyRegistration": { + "methods": [ + "delete_prediction_api_key_registration" + ] + }, + "ListPredictionApiKeyRegistrations": { + "methods": [ + "list_prediction_api_key_registrations" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "rest": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "ListUserEvents": { + "methods": [ + "list_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "ListUserEvents": { + "methods": [ + "list_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "rest": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "ListUserEvents": { + "methods": [ + "list_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_version.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_version.py new file mode 100644 index 00000000..405b1ceb --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/gapic_version.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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed new file mode 100644 index 00000000..41689a36 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-recommendations-ai package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/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/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py new file mode 100644 index 00000000..d276b897 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/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/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py new file mode 100644 index 00000000..3c84945d --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py @@ -0,0 +1,966 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import common +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.protobuf import field_mask_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 ingesting catalog information of the customer's + website. + """ + + _client: CatalogServiceClient + + DEFAULT_ENDPOINT = CatalogServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CatalogServiceClient.DEFAULT_MTLS_ENDPOINT + + catalog_path = staticmethod(CatalogServiceClient.catalog_path) + parse_catalog_path = staticmethod(CatalogServiceClient.parse_catalog_path) + catalog_item_path_path = staticmethod(CatalogServiceClient.catalog_item_path_path) + parse_catalog_item_path_path = staticmethod(CatalogServiceClient.parse_catalog_item_path_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 variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return 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: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", + client_options: Optional[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 create_catalog_item(self, + request: Optional[Union[catalog_service.CreateCatalogItemRequest, dict]] = None, + *, + parent: Optional[str] = None, + catalog_item: Optional[catalog.CatalogItem] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Creates a catalog item. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_create_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value1', 'categories_value2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.CreateCatalogItemRequest( + parent="parent_value", + catalog_item=catalog_item, + ) + + # Make the request + response = await client.create_catalog_item(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.CreateCatalogItemRequest, dict]]): + The request object. Request message for CreateCatalogItem + method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + catalog_item (:class:`google.cloud.recommendationengine_v1beta1.types.CatalogItem`): + Required. The catalog item to create. + This corresponds to the ``catalog_item`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, catalog_item]) + if request is not 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.CreateCatalogItemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if catalog_item is not None: + request.catalog_item = catalog_item + + # 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_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.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, + ) + + # Done; return the response. + return response + + async def get_catalog_item(self, + request: Optional[Union[catalog_service.GetCatalogItemRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Gets a specific catalog item. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_get_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.GetCatalogItemRequest( + name="name_value", + ) + + # Make the request + response = await client.get_catalog_item(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.GetCatalogItemRequest, dict]]): + The request object. Request message for GetCatalogItem + method. + name (:class:`str`): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_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.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not 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.GetCatalogItemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.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(( + ("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_catalog_items(self, + request: Optional[Union[catalog_service.ListCatalogItemsRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogItemsAsyncPager: + r"""Gets a list of catalog items. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_list_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalog_items(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsRequest, dict]]): + The request object. Request message for ListCatalogItems + method. + parent (:class:`str`): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. A filter to apply on the + list results. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers.ListCatalogItemsAsyncPager: + Response message for ListCatalogItems + 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, filter]) + if request is not 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.ListCatalogItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # 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_catalog_items, + default_retry=retries.Retry( +initial=0.1,maximum=60.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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCatalogItemsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_catalog_item(self, + request: Optional[Union[catalog_service.UpdateCatalogItemRequest, dict]] = None, + *, + name: Optional[str] = None, + catalog_item: Optional[catalog.CatalogItem] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Updates a catalog item. Partial updating is + supported. Non-existing items will be created. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_update_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value1', 'categories_value2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.UpdateCatalogItemRequest( + name="name_value", + catalog_item=catalog_item, + ) + + # Make the request + response = await client.update_catalog_item(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.UpdateCatalogItemRequest, dict]]): + The request object. Request message for UpdateCatalogItem + method. + name (:class:`str`): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + catalog_item (:class:`google.cloud.recommendationengine_v1beta1.types.CatalogItem`): + Required. The catalog item to update/create. The + 'catalog_item_id' field has to match that in the 'name'. + + This corresponds to the ``catalog_item`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Indicates which fields in + the provided 'item' to update. If not + set, will by default update all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, catalog_item, 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.UpdateCatalogItemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if catalog_item is not None: + request.catalog_item = catalog_item + 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_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.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(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_catalog_item(self, + request: Optional[Union[catalog_service.DeleteCatalogItemRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a catalog item. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_delete_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeleteCatalogItemRequest( + name="name_value", + ) + + # Make the request + await client.delete_catalog_item(request=request) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.DeleteCatalogItemRequest, dict]]): + The request object. Request message for DeleteCatalogItem + method. + name (:class:`str`): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_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 = catalog_service.DeleteCatalogItemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.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(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_catalog_items(self, + request: Optional[Union[import_.ImportCatalogItemsRequest, dict]] = None, + *, + parent: Optional[str] = None, + request_id: Optional[str] = None, + input_config: Optional[import_.InputConfig] = None, + errors_config: Optional[import_.ImportErrorsConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple catalog items. Request + processing may be synchronous. No partial updating + supported. Non-existing items will be created. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_import_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_catalog_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsRequest, dict]]): + The request object. Request message for Import methods. + parent (:class:`str`): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + request_id (:class:`str`): + Optional. Unique identifier provided + by client, within the ancestor dataset + scope. Ensures idempotency and used for + request deduplication. Server-generated + if unspecified. Up to 128 characters + long. This is returned as + google.longrunning.Operation.name in the + response. + + This corresponds to the ``request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (:class:`google.cloud.recommendationengine_v1beta1.types.InputConfig`): + Required. The desired input location + of the data. + + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + errors_config (:class:`google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig`): + Optional. The desired location of + errors incurred during the Import. + + This corresponds to the ``errors_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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsResponse` Response of the ImportCatalogItemsRequest. 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, request_id, input_config, errors_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 = import_.ImportCatalogItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if request_id is not None: + request.request_id = request_id + if input_config is not None: + request.input_config = input_config + if errors_config is not None: + request.errors_config = errors_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.import_catalog_items, + default_retry=retries.Retry( +initial=0.1,maximum=60.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_.ImportCatalogItemsResponse, + metadata_type=import_.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() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "CatalogServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py new file mode 100644 index 00000000..5e8c473d --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py @@ -0,0 +1,1137 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import common +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import CatalogServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CatalogServiceGrpcTransport +from .transports.grpc_asyncio import CatalogServiceGrpcAsyncIOTransport +from .transports.rest import CatalogServiceRestTransport + + +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 + _transport_registry["rest"] = CatalogServiceRestTransport + + def get_transport_class(cls, + label: Optional[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 ingesting catalog 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 = "recommendationengine.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 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 catalog_item_path_path(project: str,location: str,catalog: str,catalog_item_path: str,) -> str: + """Returns a fully-qualified catalog_item_path string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/catalogItems/{catalog_item_path}".format(project=project, location=location, catalog=catalog, catalog_item_path=catalog_item_path, ) + + @staticmethod + def parse_catalog_item_path_path(path: str) -> Dict[str,str]: + """Parses a catalog_item_path path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/catalogItems/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CatalogServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = 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 (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, 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 create_catalog_item(self, + request: Optional[Union[catalog_service.CreateCatalogItemRequest, dict]] = None, + *, + parent: Optional[str] = None, + catalog_item: Optional[catalog.CatalogItem] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Creates a catalog item. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_create_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value1', 'categories_value2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.CreateCatalogItemRequest( + parent="parent_value", + catalog_item=catalog_item, + ) + + # Make the request + response = client.create_catalog_item(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.CreateCatalogItemRequest, dict]): + The request object. Request message for CreateCatalogItem + method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): + Required. The catalog item to create. + This corresponds to the ``catalog_item`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, catalog_item]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is 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.CreateCatalogItemRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.CreateCatalogItemRequest): + request = catalog_service.CreateCatalogItemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if catalog_item is not None: + request.catalog_item = catalog_item + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_catalog_item] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_catalog_item(self, + request: Optional[Union[catalog_service.GetCatalogItemRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Gets a specific catalog item. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_get_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.GetCatalogItemRequest( + name="name_value", + ) + + # Make the request + response = client.get_catalog_item(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.GetCatalogItemRequest, dict]): + The request object. Request message for GetCatalogItem + method. + name (str): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_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.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is 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.GetCatalogItemRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.GetCatalogItemRequest): + request = catalog_service.GetCatalogItemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_catalog_item] + + # Certain fields should be provided 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_catalog_items(self, + request: Optional[Union[catalog_service.ListCatalogItemsRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCatalogItemsPager: + r"""Gets a list of catalog items. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_list_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalog_items(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsRequest, dict]): + The request object. Request message for ListCatalogItems + method. + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. A filter to apply on the + list results. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers.ListCatalogItemsPager: + Response message for ListCatalogItems + 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, filter]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is 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.ListCatalogItemsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.ListCatalogItemsRequest): + request = catalog_service.ListCatalogItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_catalog_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListCatalogItemsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_catalog_item(self, + request: Optional[Union[catalog_service.UpdateCatalogItemRequest, dict]] = None, + *, + name: Optional[str] = None, + catalog_item: Optional[catalog.CatalogItem] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> catalog.CatalogItem: + r"""Updates a catalog item. Partial updating is + supported. Non-existing items will be created. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_update_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value1', 'categories_value2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.UpdateCatalogItemRequest( + name="name_value", + catalog_item=catalog_item, + ) + + # Make the request + response = client.update_catalog_item(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.UpdateCatalogItemRequest, dict]): + The request object. Request message for UpdateCatalogItem + method. + name (str): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): + Required. The catalog item to update/create. The + 'catalog_item_id' field has to match that in the 'name'. + + This corresponds to the ``catalog_item`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Indicates which fields in + the provided 'item' to update. If not + set, will by default update all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, catalog_item, 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.UpdateCatalogItemRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.UpdateCatalogItemRequest): + request = catalog_service.UpdateCatalogItemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if catalog_item is not None: + request.catalog_item = catalog_item + 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_item] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_catalog_item(self, + request: Optional[Union[catalog_service.DeleteCatalogItemRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a catalog item. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_delete_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeleteCatalogItemRequest( + name="name_value", + ) + + # Make the request + client.delete_catalog_item(request=request) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.DeleteCatalogItemRequest, dict]): + The request object. Request message for DeleteCatalogItem + method. + name (str): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_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 catalog_service.DeleteCatalogItemRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, catalog_service.DeleteCatalogItemRequest): + request = catalog_service.DeleteCatalogItemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_catalog_item] + + # Certain fields should be 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_catalog_items(self, + request: Optional[Union[import_.ImportCatalogItemsRequest, dict]] = None, + *, + parent: Optional[str] = None, + request_id: Optional[str] = None, + input_config: Optional[import_.InputConfig] = None, + errors_config: Optional[import_.ImportErrorsConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple catalog items. Request + processing may be synchronous. No partial updating + supported. Non-existing items will be created. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_import_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_catalog_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsRequest, dict]): + The request object. Request message for Import methods. + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + request_id (str): + Optional. Unique identifier provided + by client, within the ancestor dataset + scope. Ensures idempotency and used for + request deduplication. Server-generated + if unspecified. Up to 128 characters + long. This is returned as + google.longrunning.Operation.name in the + response. + + This corresponds to the ``request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): + Required. The desired input location + of the data. + + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Optional. The desired location of + errors incurred during the Import. + + This corresponds to the ``errors_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsResponse` Response of the ImportCatalogItemsRequest. 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, request_id, input_config, errors_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 import_.ImportCatalogItemsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_.ImportCatalogItemsRequest): + request = import_.ImportCatalogItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if request_id is not None: + request.request_id = request_id + if input_config is not None: + request.input_config = input_config + if errors_config is not None: + request.errors_config = errors_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_catalog_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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_.ImportCatalogItemsResponse, + metadata_type=import_.ImportMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "CatalogServiceClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "CatalogServiceClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py new file mode 100644 index 00000000..375fae35 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/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.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service + + +class ListCatalogItemsPager: + """A pager for iterating through ``list_catalog_items`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalog_items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCatalogItems`` requests and continue to iterate + through the ``catalog_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` + attributes are available on the 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.ListCatalogItemsResponse], + request: catalog_service.ListCatalogItemsRequest, + response: catalog_service.ListCatalogItemsResponse, + *, + 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.recommendationengine_v1beta1.types.ListCatalogItemsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse): + The 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.ListCatalogItemsRequest(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.ListCatalogItemsResponse]: + 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.CatalogItem]: + for page in self.pages: + yield from page.catalog_items + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCatalogItemsAsyncPager: + """A pager for iterating through ``list_catalog_items`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalog_items`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCatalogItems`` requests and continue to iterate + through the ``catalog_items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse` + attributes are available on the 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.ListCatalogItemsResponse]], + request: catalog_service.ListCatalogItemsRequest, + response: catalog_service.ListCatalogItemsResponse, + *, + 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.recommendationengine_v1beta1.types.ListCatalogItemsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsResponse): + The 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.ListCatalogItemsRequest(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.ListCatalogItemsResponse]: + 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.CatalogItem]: + async def async_generator(): + async for page in self.pages: + for response in page.catalog_items: + 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py new file mode 100644 index 00000000..085be8a2 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 +from .rest import CatalogServiceRestTransport +from .rest import CatalogServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CatalogServiceTransport]] +_transport_registry['grpc'] = CatalogServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CatalogServiceGrpcAsyncIOTransport +_transport_registry['rest'] = CatalogServiceRestTransport + +__all__ = ( + 'CatalogServiceTransport', + 'CatalogServiceGrpcTransport', + 'CatalogServiceGrpcAsyncIOTransport', + 'CatalogServiceRestTransport', + 'CatalogServiceRestInterceptor', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py new file mode 100644 index 00000000..f5d0cd2a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.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 abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class CatalogServiceTransport(abc.ABC): + """Abstract transport class for CatalogService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'recommendationengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_catalog_item: gapic_v1.method.wrap_method( + self.create_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.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.get_catalog_item: gapic_v1.method.wrap_method( + self.get_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.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.list_catalog_items: gapic_v1.method.wrap_method( + self.list_catalog_items, + default_retry=retries.Retry( +initial=0.1,maximum=60.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.update_catalog_item: gapic_v1.method.wrap_method( + self.update_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.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.delete_catalog_item: gapic_v1.method.wrap_method( + self.delete_catalog_item, + default_retry=retries.Retry( +initial=0.1,maximum=60.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.import_catalog_items: gapic_v1.method.wrap_method( + self.import_catalog_items, + default_retry=retries.Retry( +initial=0.1,maximum=60.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, + ), + } + + 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_catalog_item(self) -> Callable[ + [catalog_service.CreateCatalogItemRequest], + Union[ + catalog.CatalogItem, + Awaitable[catalog.CatalogItem] + ]]: + raise NotImplementedError() + + @property + def get_catalog_item(self) -> Callable[ + [catalog_service.GetCatalogItemRequest], + Union[ + catalog.CatalogItem, + Awaitable[catalog.CatalogItem] + ]]: + raise NotImplementedError() + + @property + def list_catalog_items(self) -> Callable[ + [catalog_service.ListCatalogItemsRequest], + Union[ + catalog_service.ListCatalogItemsResponse, + Awaitable[catalog_service.ListCatalogItemsResponse] + ]]: + raise NotImplementedError() + + @property + def update_catalog_item(self) -> Callable[ + [catalog_service.UpdateCatalogItemRequest], + Union[ + catalog.CatalogItem, + Awaitable[catalog.CatalogItem] + ]]: + raise NotImplementedError() + + @property + def delete_catalog_item(self) -> Callable[ + [catalog_service.DeleteCatalogItemRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_catalog_items(self) -> Callable[ + [import_.ImportCatalogItemsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CatalogServiceTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py new file mode 100644 index 00000000..9e730ae6 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.longrunning import operations_pb2 # type: ignore +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 ingesting catalog 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 = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_catalog_item(self) -> Callable[ + [catalog_service.CreateCatalogItemRequest], + catalog.CatalogItem]: + r"""Return a callable for the create catalog item method over gRPC. + + Creates a catalog item. + + Returns: + Callable[[~.CreateCatalogItemRequest], + ~.CatalogItem]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: + self._stubs['create_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/CreateCatalogItem', + request_serializer=catalog_service.CreateCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['create_catalog_item'] + + @property + def get_catalog_item(self) -> Callable[ + [catalog_service.GetCatalogItemRequest], + catalog.CatalogItem]: + r"""Return a callable for the get catalog item method over gRPC. + + Gets a specific catalog item. + + Returns: + Callable[[~.GetCatalogItemRequest], + ~.CatalogItem]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_catalog_item' not in self._stubs: + self._stubs['get_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/GetCatalogItem', + request_serializer=catalog_service.GetCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['get_catalog_item'] + + @property + def list_catalog_items(self) -> Callable[ + [catalog_service.ListCatalogItemsRequest], + catalog_service.ListCatalogItemsResponse]: + r"""Return a callable for the list catalog items method over gRPC. + + Gets a list of catalog items. + + Returns: + Callable[[~.ListCatalogItemsRequest], + ~.ListCatalogItemsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_catalog_items' not in self._stubs: + self._stubs['list_catalog_items'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/ListCatalogItems', + request_serializer=catalog_service.ListCatalogItemsRequest.serialize, + response_deserializer=catalog_service.ListCatalogItemsResponse.deserialize, + ) + return self._stubs['list_catalog_items'] + + @property + def update_catalog_item(self) -> Callable[ + [catalog_service.UpdateCatalogItemRequest], + catalog.CatalogItem]: + r"""Return a callable for the update catalog item method over gRPC. + + Updates a catalog item. Partial updating is + supported. Non-existing items will be created. + + Returns: + Callable[[~.UpdateCatalogItemRequest], + ~.CatalogItem]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_item' not in self._stubs: + self._stubs['update_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/UpdateCatalogItem', + request_serializer=catalog_service.UpdateCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['update_catalog_item'] + + @property + def delete_catalog_item(self) -> Callable[ + [catalog_service.DeleteCatalogItemRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete catalog item method over gRPC. + + Deletes a catalog item. + + Returns: + Callable[[~.DeleteCatalogItemRequest], + ~.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_catalog_item' not in self._stubs: + self._stubs['delete_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/DeleteCatalogItem', + request_serializer=catalog_service.DeleteCatalogItemRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_catalog_item'] + + @property + def import_catalog_items(self) -> Callable[ + [import_.ImportCatalogItemsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import catalog items method over gRPC. + + Bulk import of multiple catalog items. Request + processing may be synchronous. No partial updating + supported. Non-existing items will be created. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully updated. + + Returns: + Callable[[~.ImportCatalogItemsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_items' not in self._stubs: + self._stubs['import_catalog_items'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/ImportCatalogItems', + request_serializer=import_.ImportCatalogItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_catalog_items'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CatalogServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..3f0e7c10 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py @@ -0,0 +1,423 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.longrunning import operations_pb2 # type: ignore +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 ingesting catalog 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 = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_catalog_item(self) -> Callable[ + [catalog_service.CreateCatalogItemRequest], + Awaitable[catalog.CatalogItem]]: + r"""Return a callable for the create catalog item method over gRPC. + + Creates a catalog item. + + Returns: + Callable[[~.CreateCatalogItemRequest], + Awaitable[~.CatalogItem]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_item' not in self._stubs: + self._stubs['create_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/CreateCatalogItem', + request_serializer=catalog_service.CreateCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['create_catalog_item'] + + @property + def get_catalog_item(self) -> Callable[ + [catalog_service.GetCatalogItemRequest], + Awaitable[catalog.CatalogItem]]: + r"""Return a callable for the get catalog item method over gRPC. + + Gets a specific catalog item. + + Returns: + Callable[[~.GetCatalogItemRequest], + Awaitable[~.CatalogItem]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_catalog_item' not in self._stubs: + self._stubs['get_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/GetCatalogItem', + request_serializer=catalog_service.GetCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['get_catalog_item'] + + @property + def list_catalog_items(self) -> Callable[ + [catalog_service.ListCatalogItemsRequest], + Awaitable[catalog_service.ListCatalogItemsResponse]]: + r"""Return a callable for the list catalog items method over gRPC. + + Gets a list of catalog items. + + Returns: + Callable[[~.ListCatalogItemsRequest], + Awaitable[~.ListCatalogItemsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_catalog_items' not in self._stubs: + self._stubs['list_catalog_items'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/ListCatalogItems', + request_serializer=catalog_service.ListCatalogItemsRequest.serialize, + response_deserializer=catalog_service.ListCatalogItemsResponse.deserialize, + ) + return self._stubs['list_catalog_items'] + + @property + def update_catalog_item(self) -> Callable[ + [catalog_service.UpdateCatalogItemRequest], + Awaitable[catalog.CatalogItem]]: + r"""Return a callable for the update catalog item method over gRPC. + + Updates a catalog item. Partial updating is + supported. Non-existing items will be created. + + Returns: + Callable[[~.UpdateCatalogItemRequest], + Awaitable[~.CatalogItem]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_item' not in self._stubs: + self._stubs['update_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/UpdateCatalogItem', + request_serializer=catalog_service.UpdateCatalogItemRequest.serialize, + response_deserializer=catalog.CatalogItem.deserialize, + ) + return self._stubs['update_catalog_item'] + + @property + def delete_catalog_item(self) -> Callable[ + [catalog_service.DeleteCatalogItemRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete catalog item method over gRPC. + + Deletes a catalog item. + + Returns: + Callable[[~.DeleteCatalogItemRequest], + 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_catalog_item' not in self._stubs: + self._stubs['delete_catalog_item'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/DeleteCatalogItem', + request_serializer=catalog_service.DeleteCatalogItemRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_catalog_item'] + + @property + def import_catalog_items(self) -> Callable[ + [import_.ImportCatalogItemsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import catalog items method over gRPC. + + Bulk import of multiple catalog items. Request + processing may be synchronous. No partial updating + supported. Non-existing items will be created. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully updated. + + Returns: + Callable[[~.ImportCatalogItemsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_catalog_items' not in self._stubs: + self._stubs['import_catalog_items'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.CatalogService/ImportCatalogItems', + request_serializer=import_.ImportCatalogItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_catalog_items'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'CatalogServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/rest.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/rest.py new file mode 100644 index 00000000..98a6d021 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/rest.py @@ -0,0 +1,907 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CatalogServiceRestInterceptor: + """Interceptor for CatalogService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CatalogServiceRestTransport. + + .. code-block:: python + class MyCustomCatalogServiceInterceptor(CatalogServiceRestInterceptor): + def pre_create_catalog_item(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_catalog_item(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_catalog_item(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_catalog_item(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_catalog_item(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_catalog_items(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_catalog_items(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_catalog_items(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_catalog_items(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_catalog_item(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_catalog_item(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CatalogServiceRestTransport(interceptor=MyCustomCatalogServiceInterceptor()) + client = CatalogServiceClient(transport=transport) + + + """ + def pre_create_catalog_item(self, request: catalog_service.CreateCatalogItemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[catalog_service.CreateCatalogItemRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_catalog_item + + Override in a subclass to manipulate the request or metadata + before they are sent to the CatalogService server. + """ + return request, metadata + + def post_create_catalog_item(self, response: catalog.CatalogItem) -> catalog.CatalogItem: + """Post-rpc interceptor for create_catalog_item + + Override in a subclass to manipulate the response + after it is returned by the CatalogService server but before + it is returned to user code. + """ + return response + def pre_delete_catalog_item(self, request: catalog_service.DeleteCatalogItemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[catalog_service.DeleteCatalogItemRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_catalog_item + + Override in a subclass to manipulate the request or metadata + before they are sent to the CatalogService server. + """ + return request, metadata + + def pre_get_catalog_item(self, request: catalog_service.GetCatalogItemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[catalog_service.GetCatalogItemRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_catalog_item + + Override in a subclass to manipulate the request or metadata + before they are sent to the CatalogService server. + """ + return request, metadata + + def post_get_catalog_item(self, response: catalog.CatalogItem) -> catalog.CatalogItem: + """Post-rpc interceptor for get_catalog_item + + Override in a subclass to manipulate the response + after it is returned by the CatalogService server but before + it is returned to user code. + """ + return response + def pre_import_catalog_items(self, request: import_.ImportCatalogItemsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_.ImportCatalogItemsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_catalog_items + + Override in a subclass to manipulate the request or metadata + before they are sent to the CatalogService server. + """ + return request, metadata + + def post_import_catalog_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for import_catalog_items + + Override in a subclass to manipulate the response + after it is returned by the CatalogService server but before + it is returned to user code. + """ + return response + def pre_list_catalog_items(self, request: catalog_service.ListCatalogItemsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[catalog_service.ListCatalogItemsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_catalog_items + + Override in a subclass to manipulate the request or metadata + before they are sent to the CatalogService server. + """ + return request, metadata + + def post_list_catalog_items(self, response: catalog_service.ListCatalogItemsResponse) -> catalog_service.ListCatalogItemsResponse: + """Post-rpc interceptor for list_catalog_items + + Override in a subclass to manipulate the response + after it is returned by the CatalogService server but before + it is returned to user code. + """ + return response + def pre_update_catalog_item(self, request: catalog_service.UpdateCatalogItemRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[catalog_service.UpdateCatalogItemRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_catalog_item + + Override in a subclass to manipulate the request or metadata + before they are sent to the CatalogService server. + """ + return request, metadata + + def post_update_catalog_item(self, response: catalog.CatalogItem) -> catalog.CatalogItem: + """Post-rpc interceptor for update_catalog_item + + Override in a subclass to manipulate the response + after it is returned by the CatalogService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CatalogServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CatalogServiceRestInterceptor + + +class CatalogServiceRestTransport(CatalogServiceTransport): + """REST backend transport for CatalogService. + + Service for ingesting catalog information of the customer's + website. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[CatalogServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CatalogServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateCatalogItem(CatalogServiceRestStub): + def __hash__(self): + return hash("CreateCatalogItem") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: catalog_service.CreateCatalogItemRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> catalog.CatalogItem: + r"""Call the create catalog item method over HTTP. + + Args: + request (~.catalog_service.CreateCatalogItemRequest): + The request object. Request message for CreateCatalogItem + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.catalog.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems', + 'body': 'catalog_item', + }, + ] + request, metadata = self._interceptor.pre_create_catalog_item(request, metadata) + pb_request = catalog_service.CreateCatalogItemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = catalog.CatalogItem() + pb_resp = catalog.CatalogItem.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_catalog_item(resp) + return resp + + class _DeleteCatalogItem(CatalogServiceRestStub): + def __hash__(self): + return hash("DeleteCatalogItem") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: catalog_service.DeleteCatalogItemRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete catalog item method over HTTP. + + Args: + request (~.catalog_service.DeleteCatalogItemRequest): + The request object. Request message for DeleteCatalogItem + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}', + }, + ] + request, metadata = self._interceptor.pre_delete_catalog_item(request, metadata) + pb_request = catalog_service.DeleteCatalogItemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetCatalogItem(CatalogServiceRestStub): + def __hash__(self): + return hash("GetCatalogItem") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: catalog_service.GetCatalogItemRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> catalog.CatalogItem: + r"""Call the get catalog item method over HTTP. + + Args: + request (~.catalog_service.GetCatalogItemRequest): + The request object. Request message for GetCatalogItem + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.catalog.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}', + }, + ] + request, metadata = self._interceptor.pre_get_catalog_item(request, metadata) + pb_request = catalog_service.GetCatalogItemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = catalog.CatalogItem() + pb_resp = catalog.CatalogItem.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_catalog_item(resp) + return resp + + class _ImportCatalogItems(CatalogServiceRestStub): + def __hash__(self): + return hash("ImportCatalogItems") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: import_.ImportCatalogItemsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the import catalog items method over HTTP. + + Args: + request (~.import_.ImportCatalogItemsRequest): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems:import', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_import_catalog_items(request, metadata) + pb_request = import_.ImportCatalogItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_catalog_items(resp) + return resp + + class _ListCatalogItems(CatalogServiceRestStub): + def __hash__(self): + return hash("ListCatalogItems") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: catalog_service.ListCatalogItemsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> catalog_service.ListCatalogItemsResponse: + r"""Call the list catalog items method over HTTP. + + Args: + request (~.catalog_service.ListCatalogItemsRequest): + The request object. Request message for ListCatalogItems + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.catalog_service.ListCatalogItemsResponse: + Response message for ListCatalogItems + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems', + }, + ] + request, metadata = self._interceptor.pre_list_catalog_items(request, metadata) + pb_request = catalog_service.ListCatalogItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = catalog_service.ListCatalogItemsResponse() + pb_resp = catalog_service.ListCatalogItemsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_catalog_items(resp) + return resp + + class _UpdateCatalogItem(CatalogServiceRestStub): + def __hash__(self): + return hash("UpdateCatalogItem") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: catalog_service.UpdateCatalogItemRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> catalog.CatalogItem: + r"""Call the update catalog item method over HTTP. + + Args: + request (~.catalog_service.UpdateCatalogItemRequest): + The request object. Request message for UpdateCatalogItem + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.catalog.CatalogItem: + CatalogItem captures all metadata + information of items to be recommended. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}', + 'body': 'catalog_item', + }, + ] + request, metadata = self._interceptor.pre_update_catalog_item(request, metadata) + pb_request = catalog_service.UpdateCatalogItemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = catalog.CatalogItem() + pb_resp = catalog.CatalogItem.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_catalog_item(resp) + return resp + + @property + def create_catalog_item(self) -> Callable[ + [catalog_service.CreateCatalogItemRequest], + catalog.CatalogItem]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCatalogItem(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_catalog_item(self) -> Callable[ + [catalog_service.DeleteCatalogItemRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCatalogItem(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_catalog_item(self) -> Callable[ + [catalog_service.GetCatalogItemRequest], + catalog.CatalogItem]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCatalogItem(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_catalog_items(self) -> Callable[ + [import_.ImportCatalogItemsRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ImportCatalogItems(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_catalog_items(self) -> Callable[ + [catalog_service.ListCatalogItemsRequest], + catalog_service.ListCatalogItemsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCatalogItems(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_catalog_item(self) -> Callable[ + [catalog_service.UpdateCatalogItemRequest], + catalog.CatalogItem]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCatalogItem(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'CatalogServiceRestTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py new file mode 100644 index 00000000..9375c691 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__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 PredictionApiKeyRegistryClient +from .async_client import PredictionApiKeyRegistryAsyncClient + +__all__ = ( + 'PredictionApiKeyRegistryClient', + 'PredictionApiKeyRegistryAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py new file mode 100644 index 00000000..e0b35937 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py @@ -0,0 +1,541 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import pagers +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from .transports.base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import PredictionApiKeyRegistryGrpcAsyncIOTransport +from .client import PredictionApiKeyRegistryClient + + +class PredictionApiKeyRegistryAsyncClient: + """Service for registering API keys for use with the ``predict`` + method. If you use an API key to request predictions, you must first + register the API key. Otherwise, your prediction request is + rejected. If you use OAuth to authenticate your ``predict`` method + call, you do not need to register an API key. You can register up to + 20 API keys per project. + """ + + _client: PredictionApiKeyRegistryClient + + DEFAULT_ENDPOINT = PredictionApiKeyRegistryClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PredictionApiKeyRegistryClient.DEFAULT_MTLS_ENDPOINT + + event_store_path = staticmethod(PredictionApiKeyRegistryClient.event_store_path) + parse_event_store_path = staticmethod(PredictionApiKeyRegistryClient.parse_event_store_path) + prediction_api_key_registration_path = staticmethod(PredictionApiKeyRegistryClient.prediction_api_key_registration_path) + parse_prediction_api_key_registration_path = staticmethod(PredictionApiKeyRegistryClient.parse_prediction_api_key_registration_path) + common_billing_account_path = staticmethod(PredictionApiKeyRegistryClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_billing_account_path) + common_folder_path = staticmethod(PredictionApiKeyRegistryClient.common_folder_path) + parse_common_folder_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_folder_path) + common_organization_path = staticmethod(PredictionApiKeyRegistryClient.common_organization_path) + parse_common_organization_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_organization_path) + common_project_path = staticmethod(PredictionApiKeyRegistryClient.common_project_path) + parse_common_project_path = staticmethod(PredictionApiKeyRegistryClient.parse_common_project_path) + common_location_path = staticmethod(PredictionApiKeyRegistryClient.common_location_path) + parse_common_location_path = staticmethod(PredictionApiKeyRegistryClient.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: + PredictionApiKeyRegistryAsyncClient: The constructed client. + """ + return PredictionApiKeyRegistryClient.from_service_account_info.__func__(PredictionApiKeyRegistryAsyncClient, 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: + PredictionApiKeyRegistryAsyncClient: The constructed client. + """ + return PredictionApiKeyRegistryClient.from_service_account_file.__func__(PredictionApiKeyRegistryAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return PredictionApiKeyRegistryClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PredictionApiKeyRegistryTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionApiKeyRegistryTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(PredictionApiKeyRegistryClient).get_transport_class, type(PredictionApiKeyRegistryClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionApiKeyRegistryTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction api key registry client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.PredictionApiKeyRegistryTransport]): 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 = PredictionApiKeyRegistryClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_prediction_api_key_registration(self, + request: Optional[Union[prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, dict]] = None, + *, + parent: Optional[str] = None, + prediction_api_key_registration: Optional[prediction_apikey_registry_service.PredictionApiKeyRegistration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_apikey_registry_service.PredictionApiKeyRegistration: + r"""Register an API key for use with predict method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_create_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CreatePredictionApiKeyRegistrationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_prediction_api_key_registration(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.CreatePredictionApiKeyRegistrationRequest, dict]]): + The request object. Request message for the + ``CreatePredictionApiKeyRegistration`` method. + parent (:class:`str`): + Required. The parent resource path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + prediction_api_key_registration (:class:`google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration`): + Required. The prediction API key + registration. + + This corresponds to the ``prediction_api_key_registration`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration: + Registered Api Key. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, prediction_api_key_registration]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if prediction_api_key_registration is not None: + request.prediction_api_key_registration = prediction_api_key_registration + + # 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_prediction_api_key_registration, + default_retry=retries.Retry( +initial=0.1,maximum=60.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, + ) + + # Done; return the response. + return response + + async def list_prediction_api_key_registrations(self, + request: Optional[Union[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPredictionApiKeyRegistrationsAsyncPager: + r"""List the registered apiKeys for use with predict + method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_list_prediction_api_key_registrations(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListPredictionApiKeyRegistrationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_prediction_api_key_registrations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest, dict]]): + The request object. Request message for the + ``ListPredictionApiKeyRegistrations``. + parent (:class:`str`): + Required. The parent placement resource name such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers.ListPredictionApiKeyRegistrationsAsyncPager: + Response message for the + ListPredictionApiKeyRegistrations. + + 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 = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(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_prediction_api_key_registrations, + default_retry=retries.Retry( +initial=0.1,maximum=60.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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPredictionApiKeyRegistrationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_prediction_api_key_registration(self, + request: Optional[Union[prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Unregister an apiKey from using for predict method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_delete_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeletePredictionApiKeyRegistrationRequest( + name="name_value", + ) + + # Make the request + await client.delete_prediction_api_key_registration(request=request) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.DeletePredictionApiKeyRegistrationRequest, dict]]): + The request object. Request message for + ``DeletePredictionApiKeyRegistration`` method. + name (:class:`str`): + Required. The API key to unregister including full + resource path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_prediction_api_key_registration, + default_retry=retries.Retry( +initial=0.1,maximum=60.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(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "PredictionApiKeyRegistryAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py new file mode 100644 index 00000000..9ae9947a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py @@ -0,0 +1,733 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import pagers +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from .transports.base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionApiKeyRegistryGrpcTransport +from .transports.grpc_asyncio import PredictionApiKeyRegistryGrpcAsyncIOTransport +from .transports.rest import PredictionApiKeyRegistryRestTransport + + +class PredictionApiKeyRegistryClientMeta(type): + """Metaclass for the PredictionApiKeyRegistry 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[PredictionApiKeyRegistryTransport]] + _transport_registry["grpc"] = PredictionApiKeyRegistryGrpcTransport + _transport_registry["grpc_asyncio"] = PredictionApiKeyRegistryGrpcAsyncIOTransport + _transport_registry["rest"] = PredictionApiKeyRegistryRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[PredictionApiKeyRegistryTransport]: + """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 PredictionApiKeyRegistryClient(metaclass=PredictionApiKeyRegistryClientMeta): + """Service for registering API keys for use with the ``predict`` + method. If you use an API key to request predictions, you must first + register the API key. Otherwise, your prediction request is + rejected. If you use OAuth to authenticate your ``predict`` method + call, you do not need to register an API key. You can register up to + 20 API keys per project. + """ + + @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 = "recommendationengine.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: + PredictionApiKeyRegistryClient: 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: + PredictionApiKeyRegistryClient: 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) -> PredictionApiKeyRegistryTransport: + """Returns the transport used by the client instance. + + Returns: + PredictionApiKeyRegistryTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def event_store_path(project: str,location: str,catalog: str,event_store: str,) -> str: + """Returns a fully-qualified event_store string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) + + @staticmethod + def parse_event_store_path(path: str) -> Dict[str,str]: + """Parses a event_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def prediction_api_key_registration_path(project: str,location: str,catalog: str,event_store: str,prediction_api_key_registration: str,) -> str: + """Returns a fully-qualified prediction_api_key_registration string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/predictionApiKeyRegistrations/{prediction_api_key_registration}".format(project=project, location=location, catalog=catalog, event_store=event_store, prediction_api_key_registration=prediction_api_key_registration, ) + + @staticmethod + def parse_prediction_api_key_registration_path(path: str) -> Dict[str,str]: + """Parses a prediction_api_key_registration path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)/predictionApiKeyRegistrations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, PredictionApiKeyRegistryTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the prediction api key registry client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, PredictionApiKeyRegistryTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, PredictionApiKeyRegistryTransport): + # transport is a PredictionApiKeyRegistryTransport 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_prediction_api_key_registration(self, + request: Optional[Union[prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, dict]] = None, + *, + parent: Optional[str] = None, + prediction_api_key_registration: Optional[prediction_apikey_registry_service.PredictionApiKeyRegistration] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> prediction_apikey_registry_service.PredictionApiKeyRegistration: + r"""Register an API key for use with predict method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_create_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CreatePredictionApiKeyRegistrationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_prediction_api_key_registration(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.CreatePredictionApiKeyRegistrationRequest, dict]): + The request object. Request message for the + ``CreatePredictionApiKeyRegistration`` method. + parent (str): + Required. The parent resource path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + prediction_api_key_registration (google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration): + Required. The prediction API key + registration. + + This corresponds to the ``prediction_api_key_registration`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration: + Registered Api Key. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, prediction_api_key_registration]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest): + request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if prediction_api_key_registration is not None: + request.prediction_api_key_registration = prediction_api_key_registration + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_prediction_api_key_registration] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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 list_prediction_api_key_registrations(self, + request: Optional[Union[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPredictionApiKeyRegistrationsPager: + r"""List the registered apiKeys for use with predict + method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_list_prediction_api_key_registrations(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListPredictionApiKeyRegistrationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_prediction_api_key_registrations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest, dict]): + The request object. Request message for the + ``ListPredictionApiKeyRegistrations``. + parent (str): + Required. The parent placement resource name such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers.ListPredictionApiKeyRegistrationsPager: + Response message for the + ListPredictionApiKeyRegistrations. + + 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 prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest): + request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(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_prediction_api_key_registrations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = 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.ListPredictionApiKeyRegistrationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_prediction_api_key_registration(self, + request: Optional[Union[prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Unregister an apiKey from using for predict method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_delete_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeletePredictionApiKeyRegistrationRequest( + name="name_value", + ) + + # Make the request + client.delete_prediction_api_key_registration(request=request) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.DeletePredictionApiKeyRegistrationRequest, dict]): + The request object. Request message for + ``DeletePredictionApiKeyRegistration`` method. + name (str): + Required. The API key to unregister including full + resource path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest): + request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_prediction_api_key_registration] + + # Certain fields should be 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 __enter__(self) -> "PredictionApiKeyRegistryClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "PredictionApiKeyRegistryClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py new file mode 100644 index 00000000..b3d3ffc5 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/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.recommendationengine_v1beta1.types import prediction_apikey_registry_service + + +class ListPredictionApiKeyRegistrationsPager: + """A pager for iterating through ``list_prediction_api_key_registrations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``prediction_api_key_registrations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPredictionApiKeyRegistrations`` requests and continue to iterate + through the ``prediction_api_key_registrations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse], + request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, + response: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse, + *, + 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.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]: + 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[prediction_apikey_registry_service.PredictionApiKeyRegistration]: + for page in self.pages: + yield from page.prediction_api_key_registrations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPredictionApiKeyRegistrationsAsyncPager: + """A pager for iterating through ``list_prediction_api_key_registrations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``prediction_api_key_registrations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPredictionApiKeyRegistrations`` requests and continue to iterate + through the ``prediction_api_key_registrations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse` + attributes are available on the 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[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]], + request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, + response: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse, + *, + 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.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]: + 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[prediction_apikey_registry_service.PredictionApiKeyRegistration]: + async def async_generator(): + async for page in self.pages: + for response in page.prediction_api_key_registrations: + 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py new file mode 100644 index 00000000..486599f2 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 PredictionApiKeyRegistryTransport +from .grpc import PredictionApiKeyRegistryGrpcTransport +from .grpc_asyncio import PredictionApiKeyRegistryGrpcAsyncIOTransport +from .rest import PredictionApiKeyRegistryRestTransport +from .rest import PredictionApiKeyRegistryRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionApiKeyRegistryTransport]] +_transport_registry['grpc'] = PredictionApiKeyRegistryGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionApiKeyRegistryGrpcAsyncIOTransport +_transport_registry['rest'] = PredictionApiKeyRegistryRestTransport + +__all__ = ( + 'PredictionApiKeyRegistryTransport', + 'PredictionApiKeyRegistryGrpcTransport', + 'PredictionApiKeyRegistryGrpcAsyncIOTransport', + 'PredictionApiKeyRegistryRestTransport', + 'PredictionApiKeyRegistryRestInterceptor', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py new file mode 100644 index 00000000..8e757f7c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/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 + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class PredictionApiKeyRegistryTransport(abc.ABC): + """Abstract transport class for PredictionApiKeyRegistry.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'recommendationengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_prediction_api_key_registration: gapic_v1.method.wrap_method( + self.create_prediction_api_key_registration, + default_retry=retries.Retry( +initial=0.1,maximum=60.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.list_prediction_api_key_registrations: gapic_v1.method.wrap_method( + self.list_prediction_api_key_registrations, + default_retry=retries.Retry( +initial=0.1,maximum=60.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.delete_prediction_api_key_registration: gapic_v1.method.wrap_method( + self.delete_prediction_api_key_registration, + default_retry=retries.Retry( +initial=0.1,maximum=60.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, + ), + } + + 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_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest], + Union[ + prediction_apikey_registry_service.PredictionApiKeyRegistration, + Awaitable[prediction_apikey_registry_service.PredictionApiKeyRegistration] + ]]: + raise NotImplementedError() + + @property + def list_prediction_api_key_registrations(self) -> Callable[ + [prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest], + Union[ + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse, + Awaitable[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'PredictionApiKeyRegistryTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py new file mode 100644 index 00000000..13dd66d0 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py @@ -0,0 +1,326 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from google.protobuf import empty_pb2 # type: ignore +from .base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO + + +class PredictionApiKeyRegistryGrpcTransport(PredictionApiKeyRegistryTransport): + """gRPC backend transport for PredictionApiKeyRegistry. + + Service for registering API keys for use with the ``predict`` + method. If you use an API key to request predictions, you must first + register the API key. Otherwise, your prediction request is + rejected. If you use OAuth to authenticate your ``predict`` method + call, you do not need to register an API key. You can register up to + 20 API keys per project. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest], + prediction_apikey_registry_service.PredictionApiKeyRegistration]: + r"""Return a callable for the create prediction api key + registration method over gRPC. + + Register an API key for use with predict method. + + Returns: + Callable[[~.CreatePredictionApiKeyRegistrationRequest], + ~.PredictionApiKeyRegistration]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_prediction_api_key_registration' not in self._stubs: + self._stubs['create_prediction_api_key_registration'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/CreatePredictionApiKeyRegistration', + request_serializer=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.serialize, + response_deserializer=prediction_apikey_registry_service.PredictionApiKeyRegistration.deserialize, + ) + return self._stubs['create_prediction_api_key_registration'] + + @property + def list_prediction_api_key_registrations(self) -> Callable[ + [prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest], + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]: + r"""Return a callable for the list prediction api key + registrations method over gRPC. + + List the registered apiKeys for use with predict + method. + + Returns: + Callable[[~.ListPredictionApiKeyRegistrationsRequest], + ~.ListPredictionApiKeyRegistrationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_prediction_api_key_registrations' not in self._stubs: + self._stubs['list_prediction_api_key_registrations'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/ListPredictionApiKeyRegistrations', + request_serializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.serialize, + response_deserializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.deserialize, + ) + return self._stubs['list_prediction_api_key_registrations'] + + @property + def delete_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete prediction api key + registration method over gRPC. + + Unregister an apiKey from using for predict method. + + Returns: + Callable[[~.DeletePredictionApiKeyRegistrationRequest], + ~.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_prediction_api_key_registration' not in self._stubs: + self._stubs['delete_prediction_api_key_registration'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/DeletePredictionApiKeyRegistration', + request_serializer=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_prediction_api_key_registration'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'PredictionApiKeyRegistryGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py new file mode 100644 index 00000000..5ca45986 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.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 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.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from google.protobuf import empty_pb2 # type: ignore +from .base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO +from .grpc import PredictionApiKeyRegistryGrpcTransport + + +class PredictionApiKeyRegistryGrpcAsyncIOTransport(PredictionApiKeyRegistryTransport): + """gRPC AsyncIO backend transport for PredictionApiKeyRegistry. + + Service for registering API keys for use with the ``predict`` + method. If you use an API key to request predictions, you must first + register the API key. Otherwise, your prediction request is + rejected. If you use OAuth to authenticate your ``predict`` method + call, you do not need to register an API key. You can register up to + 20 API keys per project. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest], + Awaitable[prediction_apikey_registry_service.PredictionApiKeyRegistration]]: + r"""Return a callable for the create prediction api key + registration method over gRPC. + + Register an API key for use with predict method. + + Returns: + Callable[[~.CreatePredictionApiKeyRegistrationRequest], + Awaitable[~.PredictionApiKeyRegistration]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_prediction_api_key_registration' not in self._stubs: + self._stubs['create_prediction_api_key_registration'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/CreatePredictionApiKeyRegistration', + request_serializer=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.serialize, + response_deserializer=prediction_apikey_registry_service.PredictionApiKeyRegistration.deserialize, + ) + return self._stubs['create_prediction_api_key_registration'] + + @property + def list_prediction_api_key_registrations(self) -> Callable[ + [prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest], + Awaitable[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]]: + r"""Return a callable for the list prediction api key + registrations method over gRPC. + + List the registered apiKeys for use with predict + method. + + Returns: + Callable[[~.ListPredictionApiKeyRegistrationsRequest], + Awaitable[~.ListPredictionApiKeyRegistrationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_prediction_api_key_registrations' not in self._stubs: + self._stubs['list_prediction_api_key_registrations'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/ListPredictionApiKeyRegistrations', + request_serializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.serialize, + response_deserializer=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.deserialize, + ) + return self._stubs['list_prediction_api_key_registrations'] + + @property + def delete_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete prediction api key + registration method over gRPC. + + Unregister an apiKey from using for predict method. + + Returns: + Callable[[~.DeletePredictionApiKeyRegistrationRequest], + 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_prediction_api_key_registration' not in self._stubs: + self._stubs['delete_prediction_api_key_registration'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry/DeletePredictionApiKeyRegistration', + request_serializer=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_prediction_api_key_registration'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'PredictionApiKeyRegistryGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/rest.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/rest.py new file mode 100644 index 00000000..4d22be45 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/rest.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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_service +from google.protobuf import empty_pb2 # type: ignore + +from .base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class PredictionApiKeyRegistryRestInterceptor: + """Interceptor for PredictionApiKeyRegistry. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PredictionApiKeyRegistryRestTransport. + + .. code-block:: python + class MyCustomPredictionApiKeyRegistryInterceptor(PredictionApiKeyRegistryRestInterceptor): + def pre_create_prediction_api_key_registration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_prediction_api_key_registration(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_prediction_api_key_registration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_list_prediction_api_key_registrations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_prediction_api_key_registrations(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PredictionApiKeyRegistryRestTransport(interceptor=MyCustomPredictionApiKeyRegistryInterceptor()) + client = PredictionApiKeyRegistryClient(transport=transport) + + + """ + def pre_create_prediction_api_key_registration(self, request: prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_prediction_api_key_registration + + Override in a subclass to manipulate the request or metadata + before they are sent to the PredictionApiKeyRegistry server. + """ + return request, metadata + + def post_create_prediction_api_key_registration(self, response: prediction_apikey_registry_service.PredictionApiKeyRegistration) -> prediction_apikey_registry_service.PredictionApiKeyRegistration: + """Post-rpc interceptor for create_prediction_api_key_registration + + Override in a subclass to manipulate the response + after it is returned by the PredictionApiKeyRegistry server but before + it is returned to user code. + """ + return response + def pre_delete_prediction_api_key_registration(self, request: prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_prediction_api_key_registration + + Override in a subclass to manipulate the request or metadata + before they are sent to the PredictionApiKeyRegistry server. + """ + return request, metadata + + def pre_list_prediction_api_key_registrations(self, request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_prediction_api_key_registrations + + Override in a subclass to manipulate the request or metadata + before they are sent to the PredictionApiKeyRegistry server. + """ + return request, metadata + + def post_list_prediction_api_key_registrations(self, response: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse) -> prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse: + """Post-rpc interceptor for list_prediction_api_key_registrations + + Override in a subclass to manipulate the response + after it is returned by the PredictionApiKeyRegistry server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PredictionApiKeyRegistryRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PredictionApiKeyRegistryRestInterceptor + + +class PredictionApiKeyRegistryRestTransport(PredictionApiKeyRegistryTransport): + """REST backend transport for PredictionApiKeyRegistry. + + Service for registering API keys for use with the ``predict`` + method. If you use an API key to request predictions, you must first + register the API key. Otherwise, your prediction request is + rejected. If you use OAuth to authenticate your ``predict`` method + call, you do not need to register an API key. You can register up to + 20 API keys per project. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[PredictionApiKeyRegistryRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or PredictionApiKeyRegistryRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreatePredictionApiKeyRegistration(PredictionApiKeyRegistryRestStub): + def __hash__(self): + return hash("CreatePredictionApiKeyRegistration") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> prediction_apikey_registry_service.PredictionApiKeyRegistration: + r"""Call the create prediction api key + registration method over HTTP. + + Args: + request (~.prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest): + The request object. Request message for the + ``CreatePredictionApiKeyRegistration`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.prediction_apikey_registry_service.PredictionApiKeyRegistration: + Registered Api Key. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/predictionApiKeyRegistrations', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_create_prediction_api_key_registration(request, metadata) + pb_request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = prediction_apikey_registry_service.PredictionApiKeyRegistration() + pb_resp = prediction_apikey_registry_service.PredictionApiKeyRegistration.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_prediction_api_key_registration(resp) + return resp + + class _DeletePredictionApiKeyRegistration(PredictionApiKeyRegistryRestStub): + def __hash__(self): + return hash("DeletePredictionApiKeyRegistration") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete prediction api key + registration method over HTTP. + + Args: + request (~.prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest): + The request object. Request message for + ``DeletePredictionApiKeyRegistration`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/predictionApiKeyRegistrations/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_prediction_api_key_registration(request, metadata) + pb_request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _ListPredictionApiKeyRegistrations(PredictionApiKeyRegistryRestStub): + def __hash__(self): + return hash("ListPredictionApiKeyRegistrations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse: + r"""Call the list prediction api key + registrations method over HTTP. + + Args: + request (~.prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest): + The request object. Request message for the + ``ListPredictionApiKeyRegistrations``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse: + Response message for the + ``ListPredictionApiKeyRegistrations``. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/predictionApiKeyRegistrations', + }, + ] + request, metadata = self._interceptor.pre_list_prediction_api_key_registrations(request, metadata) + pb_request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + pb_resp = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_prediction_api_key_registrations(resp) + return resp + + @property + def create_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest], + prediction_apikey_registry_service.PredictionApiKeyRegistration]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePredictionApiKeyRegistration(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_prediction_api_key_registration(self) -> Callable[ + [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePredictionApiKeyRegistration(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_prediction_api_key_registrations(self) -> Callable[ + [prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest], + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPredictionApiKeyRegistrations(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'PredictionApiKeyRegistryRestTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py new file mode 100644 index 00000000..7c079c80 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/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/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py new file mode 100644 index 00000000..d635d9eb --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py @@ -0,0 +1,377 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers +from google.cloud.recommendationengine_v1beta1.types import prediction_service +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +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 + + placement_path = staticmethod(PredictionServiceClient.placement_path) + parse_placement_path = staticmethod(PredictionServiceClient.parse_placement_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 variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return 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: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", + client_options: Optional[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: Optional[Union[prediction_service.PredictRequest, dict]] = None, + *, + name: Optional[str] = None, + user_event: Optional[gcr_user_event.UserEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.PredictAsyncPager: + r"""Makes a recommendation prediction. If using API Key based + authentication, the API Key must be registered using the + [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] + service. `Learn + more `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_predict(): + # Create a client + client = recommendationengine_v1beta1.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.PredictRequest( + name="name_value", + user_event=user_event, + ) + + # Make the request + page_result = client.predict(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.PredictRequest, dict]]): + The request object. Request message for Predict method. + name (:class:`str`): + Required. Full resource name of the format: + ``{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`` + The id of the recommendation engine placement. This id + is used to identify the set of models that will be used + to make the prediction. + + We currently support three placements with the following + IDs by default: + + - ``shopping_cart``: Predicts items frequently bought + together with one or more catalog items in the same + shopping session. Commonly displayed after + ``add-to-cart`` events, on product detail pages, or + on the shopping cart page. + + - ``home_page``: Predicts the next product that a user + will most likely engage with or purchase based on the + shopping or viewing history of the specified + ``userId`` or ``visitorId``. For example - + Recommendations for you. + + - ``product_detail``: Predicts the next product that a + user will most likely engage with or purchase. The + prediction is based on the shopping or viewing + history of the specified ``userId`` or ``visitorId`` + and its relevance to a specified ``CatalogItem``. + Typically used on product detail pages. For example - + More items like this. + + - ``recently_viewed_default``: Returns up to 75 items + recently viewed by the specified ``userId`` or + ``visitorId``, most recent ones first. Returns + nothing if neither of them has viewed any items yet. + For example - Recently viewed. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (:class:`google.cloud.recommendationengine_v1beta1.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. + + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers.PredictAsyncPager: + Response message for predict 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([name, user_event]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = prediction_service.PredictRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if user_event is not None: + request.user_event = user_event + + # 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_retry=retries.Retry( +initial=0.1,maximum=60.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(( + ("name", request.name), + )), + ) + + # 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.PredictAsyncPager( + 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() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "PredictionServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py new file mode 100644 index 00000000..059d54da --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py @@ -0,0 +1,574 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers +from google.cloud.recommendationengine_v1beta1.types import prediction_service +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from .transports.base import PredictionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import PredictionServiceGrpcTransport +from .transports.grpc_asyncio import PredictionServiceGrpcAsyncIOTransport +from .transports.rest import PredictionServiceRestTransport + + +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 + _transport_registry["rest"] = PredictionServiceRestTransport + + def get_transport_class(cls, + label: Optional[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 = "recommendationengine.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 placement_path(project: str,location: str,catalog: str,event_store: str,placement: str,) -> str: + """Returns a fully-qualified placement string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/placements/{placement}".format(project=project, location=location, catalog=catalog, event_store=event_store, placement=placement, ) + + @staticmethod + def parse_placement_path(path: str) -> Dict[str,str]: + """Parses a placement path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)/placements/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, PredictionServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = 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 (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, 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: Optional[Union[prediction_service.PredictRequest, dict]] = None, + *, + name: Optional[str] = None, + user_event: Optional[gcr_user_event.UserEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.PredictPager: + r"""Makes a recommendation prediction. If using API Key based + authentication, the API Key must be registered using the + [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] + service. `Learn + more `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_predict(): + # Create a client + client = recommendationengine_v1beta1.PredictionServiceClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.PredictRequest( + name="name_value", + user_event=user_event, + ) + + # Make the request + page_result = client.predict(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.PredictRequest, dict]): + The request object. Request message for Predict method. + name (str): + Required. Full resource name of the format: + ``{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`` + The id of the recommendation engine placement. This id + is used to identify the set of models that will be used + to make the prediction. + + We currently support three placements with the following + IDs by default: + + - ``shopping_cart``: Predicts items frequently bought + together with one or more catalog items in the same + shopping session. Commonly displayed after + ``add-to-cart`` events, on product detail pages, or + on the shopping cart page. + + - ``home_page``: Predicts the next product that a user + will most likely engage with or purchase based on the + shopping or viewing history of the specified + ``userId`` or ``visitorId``. For example - + Recommendations for you. + + - ``product_detail``: Predicts the next product that a + user will most likely engage with or purchase. The + prediction is based on the shopping or viewing + history of the specified ``userId`` or ``visitorId`` + and its relevance to a specified ``CatalogItem``. + Typically used on product detail pages. For example - + More items like this. + + - ``recently_viewed_default``: Returns up to 75 items + recently viewed by the specified ``userId`` or + ``visitorId``, most recent ones first. Returns + nothing if neither of them has viewed any items yet. + For example - Recently viewed. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (google.cloud.recommendationengine_v1beta1.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. + + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers.PredictPager: + Response message for predict 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([name, user_event]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # 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) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if user_event is not None: + request.user_event = user_event + + # 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(( + ("name", request.name), + )), + ) + + # 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.PredictPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "PredictionServiceClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "PredictionServiceClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py new file mode 100644 index 00000000..98337c9d --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_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.recommendationengine_v1beta1.types import prediction_service + + +class PredictPager: + """A pager for iterating through ``predict`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Predict`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., prediction_service.PredictResponse], + request: prediction_service.PredictRequest, + response: prediction_service.PredictResponse, + *, + 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.recommendationengine_v1beta1.types.PredictRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.PredictResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = prediction_service.PredictRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[prediction_service.PredictResponse]: + 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[prediction_service.PredictResponse.PredictionResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class PredictAsyncPager: + """A pager for iterating through ``predict`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Predict`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.PredictResponse` + attributes are available on the 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[prediction_service.PredictResponse]], + request: prediction_service.PredictRequest, + response: prediction_service.PredictResponse, + *, + 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.recommendationengine_v1beta1.types.PredictRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.PredictResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = prediction_service.PredictRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[prediction_service.PredictResponse]: + 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[prediction_service.PredictResponse.PredictionResult]: + 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py new file mode 100644 index 00000000..df85da89 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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 +from .rest import PredictionServiceRestTransport +from .rest import PredictionServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PredictionServiceTransport]] +_transport_registry['grpc'] = PredictionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = PredictionServiceGrpcAsyncIOTransport +_transport_registry['rest'] = PredictionServiceRestTransport + +__all__ = ( + 'PredictionServiceTransport', + 'PredictionServiceGrpcTransport', + 'PredictionServiceGrpcAsyncIOTransport', + 'PredictionServiceRestTransport', + 'PredictionServiceRestInterceptor', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py new file mode 100644 index 00000000..e10dd0ad --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import prediction_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class PredictionServiceTransport(abc.ABC): + """Abstract transport class for PredictionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'recommendationengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.predict: gapic_v1.method.wrap_method( + self.predict, + default_retry=retries.Retry( +initial=0.1,maximum=60.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, + ), + } + + 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py new file mode 100644 index 00000000..2c7a3a40 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_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.recommendationengine_v1beta1.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 = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. If using API Key based + authentication, the API Key must be registered using the + [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] + service. `Learn + more `__. + + 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.recommendationengine.v1beta1.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/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..2d67c754 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_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.recommendationengine_v1beta1.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 = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + Awaitable[prediction_service.PredictResponse]]: + r"""Return a callable for the predict method over gRPC. + + Makes a recommendation prediction. If using API Key based + authentication, the API Key must be registered using the + [PredictionApiKeyRegistry][google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry] + service. `Learn + more `__. + + 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.recommendationengine.v1beta1.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/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/rest.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/rest.py new file mode 100644 index 00000000..156ca95a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/rest.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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.recommendationengine_v1beta1.types import prediction_service + +from .base import PredictionServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class PredictionServiceRestInterceptor: + """Interceptor for PredictionService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PredictionServiceRestTransport. + + .. code-block:: python + class MyCustomPredictionServiceInterceptor(PredictionServiceRestInterceptor): + def pre_predict(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_predict(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PredictionServiceRestTransport(interceptor=MyCustomPredictionServiceInterceptor()) + client = PredictionServiceClient(transport=transport) + + + """ + def pre_predict(self, request: prediction_service.PredictRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[prediction_service.PredictRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for predict + + Override in a subclass to manipulate the request or metadata + before they are sent to the PredictionService server. + """ + return request, metadata + + def post_predict(self, response: prediction_service.PredictResponse) -> prediction_service.PredictResponse: + """Post-rpc interceptor for predict + + Override in a subclass to manipulate the response + after it is returned by the PredictionService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PredictionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PredictionServiceRestInterceptor + + +class PredictionServiceRestTransport(PredictionServiceTransport): + """REST 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[PredictionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or PredictionServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Predict(PredictionServiceRestStub): + def __hash__(self): + return hash("Predict") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: prediction_service.PredictRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> prediction_service.PredictResponse: + r"""Call the predict method over HTTP. + + Args: + request (~.prediction_service.PredictRequest): + 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: + ~.prediction_service.PredictResponse: + Response message for predict method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/placements/*}:predict', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_predict(request, metadata) + pb_request = prediction_service.PredictRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = prediction_service.PredictResponse() + pb_resp = prediction_service.PredictResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_predict(resp) + return resp + + @property + def predict(self) -> Callable[ + [prediction_service.PredictRequest], + prediction_service.PredictResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Predict(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'PredictionServiceRestTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py new file mode 100644 index 00000000..5f5171c1 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/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/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py new file mode 100644 index 00000000..3668fe4c --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py @@ -0,0 +1,1029 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.recommendationengine_v1beta1.services.user_event_service import pagers +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.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 + + event_store_path = staticmethod(UserEventServiceClient.event_store_path) + parse_event_store_path = staticmethod(UserEventServiceClient.parse_event_store_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_event: Optional[gcr_user_event.UserEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_write_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.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 (Optional[Union[google.cloud.recommendationengine_v1beta1.types.WriteUserEventRequest, dict]]): + The request object. Request message for WriteUserEvent + method. + parent (:class:`str`): + Required. The parent eventStore resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (:class:`google.cloud.recommendationengine_v1beta1.types.UserEvent`): + Required. User event to write. + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.UserEvent: + UserEvent captures all metadata + information recommendation engine needs + to know about how end users interact + with customers' website. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, user_event]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = user_event_service.WriteUserEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_event is not None: + request.user_event = user_event + + # 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_retry=retries.Retry( +initial=0.1,maximum=60.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, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_event: Optional[str] = None, + uri: Optional[str] = None, + ets: Optional[int] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Recommendations AI + JavaScript pixel. Users should not call this method + directly. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_collect_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.CollectUserEventRequest, dict]]): + The request object. Request message for CollectUserEvent + method. + parent (:class:`str`): + Required. The parent eventStore name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (:class:`str`): + Required. URL encoded UserEvent + proto. + + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + uri (:class:`str`): + Optional. The url including + cgi-parameters but excluding the hash + fragment. The URL must be truncated to + 1.5K bytes to conservatively be under + the 2K bytes. This is often more useful + than the referer url, because many + browsers only send the domain for 3rd + party requests. + + This corresponds to the ``uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ets (:class:`int`): + Optional. The event timestamp in + milliseconds. This prevents browser + caching of otherwise identical get + requests. The name is abbreviated to + reduce the payload bytes. + + This corresponds to the ``ets`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, user_event, uri, ets]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = user_event_service.CollectUserEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_event is not None: + request.user_event = user_event + if uri is not None: + request.uri = uri + if ets is not None: + request.ets = ets + + # 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_retry=retries.Retry( +initial=0.1,maximum=60.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, + ) + + # Done; return the response. + return response + + async def list_user_events(self, + request: Optional[Union[user_event_service.ListUserEventsRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUserEventsAsyncPager: + r"""Gets a list of user events within a time range, with + potential filtering. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_list_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListUserEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.ListUserEventsRequest, dict]]): + The request object. Request message for ListUserEvents + method. + parent (:class:`str`): + Required. The parent eventStore resource name, such as + ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Optional. Filtering expression to specify restrictions + over returned events. This is a sequence of terms, where + each term applies some kind of a restriction to the + returned user events. Use this expression to restrict + results to a specific time range, or filter events by + eventType. eg: eventTime > "2012-04-23T18:25:43.511Z" + eventsMissingCatalogItems + eventTime<"2012-04-23T18:25:43.511Z" eventType=search + + We expect only 3 types of fields: + + :: + + * eventTime: this can be specified a maximum of 2 times, once with a + less than operator and once with a greater than operator. The + eventTime restrict should result in one contiguous valid eventTime + range. + + * eventType: only 1 eventType restriction can be specified. + + * eventsMissingCatalogItems: specififying this will restrict results + to events for which catalog items were not found in the catalog. The + default behavior is to return only those events for which catalog + items were found. + + Some examples of valid filters expressions: + + - Example 1: eventTime > "2012-04-23T18:25:43.511Z" + eventTime < "2012-04-23T18:30:43.511Z" + - Example 2: eventTime > "2012-04-23T18:25:43.511Z" + eventType = detail-page-view + - Example 3: eventsMissingCatalogItems eventType = + search eventTime < "2018-04-23T18:30:43.511Z" + - Example 4: eventTime > "2012-04-23T18:25:43.511Z" + - Example 5: eventType = search + - Example 6: eventsMissingCatalogItems + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers.ListUserEventsAsyncPager: + Response message for ListUserEvents + 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, filter]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = user_event_service.ListUserEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # 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_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=60.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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListUserEventsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: Optional[Union[user_event_service.PurgeUserEventsRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + force: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_purge_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.PurgeUserEventsRequest, dict]]): + The request object. Request message for PurgeUserEvents + method. + parent (:class:`str`): + Required. The resource name of the event_store under + which the events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + Required. The filter string to specify the events to be + deleted. Empty string filter is not allowed. This filter + can also be used with ListUserEvents API to list events + that will be deleted. The eligible fields for filtering + are: + + - eventType - UserEvent.eventType field of type string. + - eventTime - in ISO 8601 "zulu" format. + - visitorId - field of type string. Specifying this + will delete all events associated with a visitor. + - userId - field of type string. Specifying this will + delete all events associated with a user. Example 1: + Deleting all events in a time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + Example 2: Deleting specific eventType in time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + Example 3: Deleting all events for a specific visitor + ``visitorId = visitor1024`` The filtering fields are + assumed to have an implicit AND. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (:class:`bool`): + Optional. The default value is false. + Override this flag to true to actually + perform the purge. If the field is not + set to true, a sampling of events to be + deleted will be returned. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.recommendationengine_v1beta1.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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter, force]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = user_event_service.PurgeUserEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + if force is not None: + request.force = force + + # 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=60.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, + user_event_service.PurgeUserEventsResponse, + metadata_type=user_event_service.PurgeUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Optional[Union[import_.ImportUserEventsRequest, dict]] = None, + *, + parent: Optional[str] = None, + request_id: Optional[str] = None, + input_config: Optional[import_.InputConfig] = None, + errors_config: Optional[import_.ImportErrorsConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + async def sample_import_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.recommendationengine_v1beta1.types.ImportUserEventsRequest, dict]]): + The request object. Request message for the + ImportUserEvents request. + parent (:class:`str`): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + request_id (:class:`str`): + Optional. Unique identifier provided by client, within + the ancestor dataset scope. Ensures idempotency for + expensive long running operations. Server-generated if + unspecified. Up to 128 characters long. This is returned + as google.longrunning.Operation.name in the response. + Note that this field must not be set if the desired + input config is catalog_inline_source. + + This corresponds to the ``request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (:class:`google.cloud.recommendationengine_v1beta1.types.InputConfig`): + Required. The desired input location + of the data. + + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + errors_config (:class:`google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig`): + Optional. The desired location of + errors incurred during the Import. + + This corresponds to the ``errors_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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.recommendationengine_v1beta1.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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, request_id, input_config, errors_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 = import_.ImportUserEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if request_id is not None: + request.request_id = request_id + if input_config is not None: + request.input_config = input_config + if errors_config is not None: + request.errors_config = errors_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.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=60.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_.ImportUserEventsResponse, + metadata_type=import_.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() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py new file mode 100644 index 00000000..61d454a1 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py @@ -0,0 +1,1198 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.recommendationengine_v1beta1.services.user_event_service import pagers +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.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 +from .transports.rest import UserEventServiceRestTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + _transport_registry["rest"] = UserEventServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[UserEventServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on 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 = "recommendationengine.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 event_store_path(project: str,location: str,catalog: str,event_store: str,) -> str: + """Returns a fully-qualified event_store string.""" + return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) + + @staticmethod + def parse_event_store_path(path: str) -> Dict[str,str]: + """Parses a event_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, UserEventServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def write_user_event(self, + request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_event: Optional[gcr_user_event.UserEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcr_user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_write_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.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.recommendationengine_v1beta1.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + parent (str): + Required. The parent eventStore resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (google.cloud.recommendationengine_v1beta1.types.UserEvent): + Required. User event to write. + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.types.UserEvent: + UserEvent captures all metadata + information recommendation engine needs + to know about how end users interact + with customers' website. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, user_event]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # 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) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_event is not None: + request.user_event = user_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + user_event: Optional[str] = None, + uri: Optional[str] = None, + ets: Optional[int] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a 3rd party domain. + This method is used only by the Recommendations AI + JavaScript pixel. Users should not call this method + directly. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_collect_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.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.recommendationengine_v1beta1.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + parent (str): + Required. The parent eventStore name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_event (str): + Required. URL encoded UserEvent + proto. + + This corresponds to the ``user_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + uri (str): + Optional. The url including + cgi-parameters but excluding the hash + fragment. The URL must be truncated to + 1.5K bytes to conservatively be under + the 2K bytes. This is often more useful + than the referer url, because many + browsers only send the domain for 3rd + party requests. + + This corresponds to the ``uri`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ets (int): + Optional. The event timestamp in + milliseconds. This prevents browser + caching of otherwise identical get + requests. The name is abbreviated to + reduce the payload bytes. + + This corresponds to the ``ets`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, user_event, uri, ets]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # 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) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user_event is not None: + request.user_event = user_event + if uri is not None: + request.uri = uri + if ets is not None: + request.ets = ets + + # 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 list_user_events(self, + request: Optional[Union[user_event_service.ListUserEventsRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListUserEventsPager: + r"""Gets a list of user events within a time range, with + potential filtering. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_list_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListUserEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_events(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.ListUserEventsRequest, dict]): + The request object. Request message for ListUserEvents + method. + parent (str): + Required. The parent eventStore resource name, such as + ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Optional. Filtering expression to specify restrictions + over returned events. This is a sequence of terms, where + each term applies some kind of a restriction to the + returned user events. Use this expression to restrict + results to a specific time range, or filter events by + eventType. eg: eventTime > "2012-04-23T18:25:43.511Z" + eventsMissingCatalogItems + eventTime<"2012-04-23T18:25:43.511Z" eventType=search + + We expect only 3 types of fields: + + :: + + * eventTime: this can be specified a maximum of 2 times, once with a + less than operator and once with a greater than operator. The + eventTime restrict should result in one contiguous valid eventTime + range. + + * eventType: only 1 eventType restriction can be specified. + + * eventsMissingCatalogItems: specififying this will restrict results + to events for which catalog items were not found in the catalog. The + default behavior is to return only those events for which catalog + items were found. + + Some examples of valid filters expressions: + + - Example 1: eventTime > "2012-04-23T18:25:43.511Z" + eventTime < "2012-04-23T18:30:43.511Z" + - Example 2: eventTime > "2012-04-23T18:25:43.511Z" + eventType = detail-page-view + - Example 3: eventsMissingCatalogItems eventType = + search eventTime < "2018-04-23T18:30:43.511Z" + - Example 4: eventTime > "2012-04-23T18:25:43.511Z" + - Example 5: eventType = search + - Example 6: eventsMissingCatalogItems + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers.ListUserEventsPager: + Response message for ListUserEvents + 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, filter]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.ListUserEventsRequest. + # 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.ListUserEventsRequest): + request = user_event_service.ListUserEventsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListUserEventsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: Optional[Union[user_event_service.PurgeUserEventsRequest, dict]] = None, + *, + parent: Optional[str] = None, + filter: Optional[str] = None, + force: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_purge_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.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.recommendationengine_v1beta1.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + parent (str): + Required. The resource name of the event_store under + which the events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + Required. The filter string to specify the events to be + deleted. Empty string filter is not allowed. This filter + can also be used with ListUserEvents API to list events + that will be deleted. The eligible fields for filtering + are: + + - eventType - UserEvent.eventType field of type string. + - eventTime - in ISO 8601 "zulu" format. + - visitorId - field of type string. Specifying this + will delete all events associated with a visitor. + - userId - field of type string. Specifying this will + delete all events associated with a user. Example 1: + Deleting all events in a time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + Example 2: Deleting specific eventType in time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + Example 3: Deleting all events for a specific visitor + ``visitorId = visitor1024`` The filtering fields are + assumed to have an implicit AND. + + This corresponds to the ``filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (bool): + Optional. The default value is false. + Override this flag to true to actually + perform the purge. If the field is not + set to true, a sampling of events to be + deleted will be returned. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.recommendationengine_v1beta1.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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, filter, force]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.PurgeUserEventsRequest. + # 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.PurgeUserEventsRequest): + request = user_event_service.PurgeUserEventsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if filter is not None: + request.filter = filter + if force is not None: + request.force = force + + # 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, + user_event_service.PurgeUserEventsResponse, + metadata_type=user_event_service.PurgeUserEventsMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Optional[Union[import_.ImportUserEventsRequest, dict]] = None, + *, + parent: Optional[str] = None, + request_id: Optional[str] = None, + input_config: Optional[import_.InputConfig] = None, + errors_config: Optional[import_.ImportErrorsConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import recommendationengine_v1beta1 + + def sample_import_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.recommendationengine_v1beta1.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + request_id (str): + Optional. Unique identifier provided by client, within + the ancestor dataset scope. Ensures idempotency for + expensive long running operations. Server-generated if + unspecified. Up to 128 characters long. This is returned + as google.longrunning.Operation.name in the response. + Note that this field must not be set if the desired + input config is catalog_inline_source. + + This corresponds to the ``request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): + Required. The desired input location + of the data. + + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Optional. The desired location of + errors incurred during the Import. + + This corresponds to the ``errors_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.recommendationengine_v1beta1.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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, request_id, input_config, errors_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 import_.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_.ImportUserEventsRequest): + request = import_.ImportUserEventsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if request_id is not None: + request.request_id = request_id + if input_config is not None: + request.input_config = input_config + if errors_config is not None: + request.errors_config = errors_config + + # 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_.ImportUserEventsResponse, + metadata_type=import_.ImportMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "UserEventServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py new file mode 100644 index 00000000..fb5bd912 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_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.recommendationengine_v1beta1.types import user_event +from google.cloud.recommendationengine_v1beta1.types import user_event_service + + +class ListUserEventsPager: + """A pager for iterating through ``list_user_events`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``user_events`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUserEvents`` requests and continue to iterate + through the ``user_events`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., user_event_service.ListUserEventsResponse], + request: user_event_service.ListUserEventsRequest, + response: user_event_service.ListUserEventsResponse, + *, + 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.recommendationengine_v1beta1.types.ListUserEventsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = user_event_service.ListUserEventsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[user_event_service.ListUserEventsResponse]: + 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[user_event.UserEvent]: + for page in self.pages: + yield from page.user_events + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUserEventsAsyncPager: + """A pager for iterating through ``list_user_events`` requests. + + This class thinly wraps an initial + :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``user_events`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUserEvents`` requests and continue to iterate + through the ``user_events`` field on the + corresponding responses. + + All the usual :class:`google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse` + attributes are available on the 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[user_event_service.ListUserEventsResponse]], + request: user_event_service.ListUserEventsRequest, + response: user_event_service.ListUserEventsResponse, + *, + 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.recommendationengine_v1beta1.types.ListUserEventsRequest): + The initial request object. + response (google.cloud.recommendationengine_v1beta1.types.ListUserEventsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = user_event_service.ListUserEventsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[user_event_service.ListUserEventsResponse]: + 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[user_event.UserEvent]: + async def async_generator(): + async for page in self.pages: + for response in page.user_events: + 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py new file mode 100644 index 00000000..4838463d --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .rest import UserEventServiceRestTransport +from .rest import UserEventServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport +_transport_registry['rest'] = UserEventServiceRestTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', + 'UserEventServiceRestTransport', + 'UserEventServiceRestInterceptor', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py new file mode 100644 index 00000000..8778d892 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py @@ -0,0 +1,249 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.recommendationengine_v1beta1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'recommendationengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_retry=retries.Retry( +initial=0.1,maximum=60.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.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_retry=retries.Retry( +initial=0.1,maximum=60.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.list_user_events: gapic_v1.method.wrap_method( + self.list_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=60.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.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=60.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.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=0.1,maximum=60.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, + ), + } + + 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[ + gcr_user_event.UserEvent, + Awaitable[gcr_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 list_user_events(self) -> Callable[ + [user_event_service.ListUserEventsRequest], + Union[ + user_event_service.ListUserEventsResponse, + Awaitable[user_event_service.ListUserEventsResponse] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [user_event_service.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_.ImportUserEventsRequest], + 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/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py new file mode 100644 index 00000000..62c94cad --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py @@ -0,0 +1,407 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.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 = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + gcr_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.recommendationengine.v1beta1.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=gcr_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 Recommendations AI + JavaScript pixel. 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.recommendationengine.v1beta1.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def list_user_events(self) -> Callable[ + [user_event_service.ListUserEventsRequest], + user_event_service.ListUserEventsResponse]: + r"""Return a callable for the list user events method over gRPC. + + Gets a list of user events within a time range, with + potential filtering. + + Returns: + Callable[[~.ListUserEventsRequest], + ~.ListUserEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_user_events' not in self._stubs: + self._stubs['list_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/ListUserEvents', + request_serializer=user_event_service.ListUserEventsRequest.serialize, + response_deserializer=user_event_service.ListUserEventsResponse.deserialize, + ) + return self._stubs['list_user_events'] + + @property + def purge_user_events(self) -> Callable[ + [user_event_service.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.recommendationengine.v1beta1.UserEventService/PurgeUserEvents', + request_serializer=user_event_service.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_.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.recommendationengine.v1beta1.UserEventService/ImportUserEvents', + request_serializer=import_.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..93aab807 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,406 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.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 = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[gcr_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.recommendationengine.v1beta1.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=gcr_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 Recommendations AI + JavaScript pixel. 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.recommendationengine.v1beta1.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def list_user_events(self) -> Callable[ + [user_event_service.ListUserEventsRequest], + Awaitable[user_event_service.ListUserEventsResponse]]: + r"""Return a callable for the list user events method over gRPC. + + Gets a list of user events within a time range, with + potential filtering. + + Returns: + Callable[[~.ListUserEventsRequest], + Awaitable[~.ListUserEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_user_events' not in self._stubs: + self._stubs['list_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.recommendationengine.v1beta1.UserEventService/ListUserEvents', + request_serializer=user_event_service.ListUserEventsRequest.serialize, + response_deserializer=user_event_service.ListUserEventsResponse.deserialize, + ) + return self._stubs['list_user_events'] + + @property + def purge_user_events(self) -> Callable[ + [user_event_service.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.recommendationengine.v1beta1.UserEventService/PurgeUserEvents', + request_serializer=user_event_service.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_.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.recommendationengine.v1beta1.UserEventService/ImportUserEvents', + request_serializer=import_.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/rest.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/rest.py new file mode 100644 index 00000000..c3e674a3 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/rest.py @@ -0,0 +1,869 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class UserEventServiceRestInterceptor: + """Interceptor for UserEventService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the UserEventServiceRestTransport. + + .. code-block:: python + class MyCustomUserEventServiceInterceptor(UserEventServiceRestInterceptor): + def pre_collect_user_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_collect_user_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_user_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_user_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_user_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_user_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_purge_user_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_purge_user_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_write_user_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_write_user_event(self, response): + logging.log(f"Received response: {response}") + return response + + transport = UserEventServiceRestTransport(interceptor=MyCustomUserEventServiceInterceptor()) + client = UserEventServiceClient(transport=transport) + + + """ + def pre_collect_user_event(self, request: user_event_service.CollectUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.CollectUserEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for collect_user_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_collect_user_event(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: + """Post-rpc interceptor for collect_user_event + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + def pre_import_user_events(self, request: import_.ImportUserEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_.ImportUserEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_user_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_import_user_events(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for import_user_events + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + def pre_list_user_events(self, request: user_event_service.ListUserEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.ListUserEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_user_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_list_user_events(self, response: user_event_service.ListUserEventsResponse) -> user_event_service.ListUserEventsResponse: + """Post-rpc interceptor for list_user_events + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + def pre_purge_user_events(self, request: user_event_service.PurgeUserEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.PurgeUserEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for purge_user_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_purge_user_events(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for purge_user_events + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + def pre_write_user_event(self, request: user_event_service.WriteUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.WriteUserEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for write_user_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_write_user_event(self, response: gcr_user_event.UserEvent) -> gcr_user_event.UserEvent: + """Post-rpc interceptor for write_user_event + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class UserEventServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: UserEventServiceRestInterceptor + + +class UserEventServiceRestTransport(UserEventServiceTransport): + """REST backend transport for UserEventService. + + Service for ingesting end user actions on 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 JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'recommendationengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[UserEventServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or UserEventServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CollectUserEvent(UserEventServiceRestStub): + def __hash__(self): + return hash("CollectUserEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userEvent" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: user_event_service.CollectUserEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> httpbody_pb2.HttpBody: + r"""Call the collect user event method over HTTP. + + Args: + request (~.user_event_service.CollectUserEventRequest): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It + should only be used for payload formats that can't be + represented as JSON, such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as the + response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request fields + and also want access to the raw HTTP body. + + Example: + + :: + + message GetResourceRequest { + // A unique request id. + string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + :: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:collect', + }, + ] + request, metadata = self._interceptor.pre_collect_user_event(request, metadata) + pb_request = user_event_service.CollectUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = httpbody_pb2.HttpBody() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_collect_user_event(resp) + return resp + + class _ImportUserEvents(UserEventServiceRestStub): + def __hash__(self): + return hash("ImportUserEvents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: import_.ImportUserEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the import user events method over HTTP. + + Args: + request (~.import_.ImportUserEventsRequest): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:import', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_import_user_events(request, metadata) + pb_request = import_.ImportUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_user_events(resp) + return resp + + class _ListUserEvents(UserEventServiceRestStub): + def __hash__(self): + return hash("ListUserEvents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: user_event_service.ListUserEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> user_event_service.ListUserEventsResponse: + r"""Call the list user events method over HTTP. + + Args: + request (~.user_event_service.ListUserEventsRequest): + The request object. Request message for ListUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.user_event_service.ListUserEventsResponse: + Response message for ListUserEvents + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents', + }, + ] + request, metadata = self._interceptor.pre_list_user_events(request, metadata) + pb_request = user_event_service.ListUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = user_event_service.ListUserEventsResponse() + pb_resp = user_event_service.ListUserEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_user_events(resp) + return resp + + class _PurgeUserEvents(UserEventServiceRestStub): + def __hash__(self): + return hash("PurgeUserEvents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: user_event_service.PurgeUserEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the purge user events method over HTTP. + + Args: + request (~.user_event_service.PurgeUserEventsRequest): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:purge', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_purge_user_events(request, metadata) + pb_request = user_event_service.PurgeUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_purge_user_events(resp) + return resp + + class _WriteUserEvent(UserEventServiceRestStub): + def __hash__(self): + return hash("WriteUserEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: user_event_service.WriteUserEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcr_user_event.UserEvent: + r"""Call the write user event method over HTTP. + + Args: + request (~.user_event_service.WriteUserEventRequest): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcr_user_event.UserEvent: + UserEvent captures all metadata + information recommendation engine needs + to know about how end users interact + with customers' website. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:write', + 'body': 'user_event', + }, + ] + request, metadata = self._interceptor.pre_write_user_event(request, metadata) + pb_request = user_event_service.WriteUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcr_user_event.UserEvent() + pb_resp = gcr_user_event.UserEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_write_user_event(resp) + return resp + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CollectUserEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_user_events(self) -> Callable[ + [import_.ImportUserEventsRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ImportUserEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_user_events(self) -> Callable[ + [user_event_service.ListUserEventsRequest], + user_event_service.ListUserEventsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListUserEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def purge_user_events(self) -> Callable[ + [user_event_service.PurgeUserEventsRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._PurgeUserEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + gcr_user_event.UserEvent]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._WriteUserEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'UserEventServiceRestTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py new file mode 100644 index 00000000..d6d68f65 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/__init__.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 ( + CatalogItem, + Image, + ProductCatalogItem, +) +from .catalog_service import ( + CreateCatalogItemRequest, + DeleteCatalogItemRequest, + GetCatalogItemRequest, + ListCatalogItemsRequest, + ListCatalogItemsResponse, + UpdateCatalogItemRequest, +) +from .common import ( + FeatureMap, +) +from .import_ import ( + CatalogInlineSource, + GcsSource, + ImportCatalogItemsRequest, + ImportCatalogItemsResponse, + ImportErrorsConfig, + ImportMetadata, + ImportUserEventsRequest, + ImportUserEventsResponse, + InputConfig, + UserEventImportSummary, + UserEventInlineSource, +) +from .prediction_apikey_registry_service import ( + CreatePredictionApiKeyRegistrationRequest, + DeletePredictionApiKeyRegistrationRequest, + ListPredictionApiKeyRegistrationsRequest, + ListPredictionApiKeyRegistrationsResponse, + PredictionApiKeyRegistration, +) +from .prediction_service import ( + PredictRequest, + PredictResponse, +) +from .user_event import ( + EventDetail, + ProductDetail, + ProductEventDetail, + PurchaseTransaction, + UserEvent, + UserInfo, +) +from .user_event_service import ( + CollectUserEventRequest, + ListUserEventsRequest, + ListUserEventsResponse, + PurgeUserEventsMetadata, + PurgeUserEventsRequest, + PurgeUserEventsResponse, + WriteUserEventRequest, +) + +__all__ = ( + 'CatalogItem', + 'Image', + 'ProductCatalogItem', + 'CreateCatalogItemRequest', + 'DeleteCatalogItemRequest', + 'GetCatalogItemRequest', + 'ListCatalogItemsRequest', + 'ListCatalogItemsResponse', + 'UpdateCatalogItemRequest', + 'FeatureMap', + 'CatalogInlineSource', + 'GcsSource', + 'ImportCatalogItemsRequest', + 'ImportCatalogItemsResponse', + 'ImportErrorsConfig', + 'ImportMetadata', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'InputConfig', + 'UserEventImportSummary', + 'UserEventInlineSource', + 'CreatePredictionApiKeyRegistrationRequest', + 'DeletePredictionApiKeyRegistrationRequest', + 'ListPredictionApiKeyRegistrationsRequest', + 'ListPredictionApiKeyRegistrationsResponse', + 'PredictionApiKeyRegistration', + 'PredictRequest', + 'PredictResponse', + 'EventDetail', + 'ProductDetail', + 'ProductEventDetail', + 'PurchaseTransaction', + 'UserEvent', + 'UserInfo', + 'CollectUserEventRequest', + 'ListUserEventsRequest', + 'ListUserEventsResponse', + 'PurgeUserEventsMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py new file mode 100644 index 00000000..404c2662 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog.py @@ -0,0 +1,349 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import common + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'CatalogItem', + 'ProductCatalogItem', + 'Image', + }, +) + + +class CatalogItem(proto.Message): + r"""CatalogItem captures all metadata information of items to be + recommended. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + Required. Catalog item identifier. UTF-8 + encoded string with a length limit of 128 bytes. + This id must be unique among all catalog items + within the same catalog. It should also be used + when logging user events in order for the user + events to be joined with the Catalog. + category_hierarchies (MutableSequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem.CategoryHierarchy]): + Required. Catalog item categories. This field is repeated + for supporting one catalog item belonging to several + parallel category hierarchies. + + For example, if a shoes product belongs to both ["Shoes & + Accessories" -> "Shoes"] and ["Sports & Fitness" -> + "Athletic Clothing" -> "Shoes"], it could be represented as: + + :: + + "categoryHierarchies": [ + { "categories": ["Shoes & Accessories", "Shoes"]}, + { "categories": ["Sports & Fitness", "Athletic Clothing", "Shoes"] } + ] + title (str): + Required. Catalog item title. UTF-8 encoded + string with a length limit of 1 KiB. + description (str): + Optional. Catalog item description. UTF-8 + encoded string with a length limit of 5 KiB. + item_attributes (google.cloud.recommendationengine_v1beta1.types.FeatureMap): + Optional. Highly encouraged. Extra catalog + item attributes to be included in the + recommendation model. For example, for retail + 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 item attributes here. + language_code (str): + Optional. Language of the title/description/item_attributes. + Use language tags defined by BCP 47. + https://www.rfc-editor.org/rfc/bcp/bcp47.txt. Our supported + language codes include 'en', 'es', 'fr', 'de', 'ar', 'fa', + 'zh', 'ja', 'ko', 'sv', 'ro', 'nl'. For other languages, + contact your Google account manager. + tags (MutableSequence[str]): + Optional. Filtering tags associated with the + catalog item. Each tag should be a UTF-8 encoded + string with a length limit of 1 KiB. + This tag can be used for filtering + recommendation results by passing the tag as + part of the predict request filter. + item_group_id (str): + Optional. Variant group identifier for prediction results. + UTF-8 encoded string with a length limit of 128 bytes. + + This field must be enabled before it can be used. `Learn + more `__. + product_metadata (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem): + Optional. Metadata specific to retail + products. + + This field is a member of `oneof`_ ``recommendation_type``. + """ + + class CategoryHierarchy(proto.Message): + r"""Category represents catalog item category hierarchy. + + Attributes: + categories (MutableSequence[str]): + Required. Catalog item categories. Each + category should be a UTF-8 encoded string with a + length limit of 2 KiB. + Note that the order in the list denotes the + specificity (from least to most specific). + """ + + categories: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + id: str = proto.Field( + proto.STRING, + number=1, + ) + category_hierarchies: MutableSequence[CategoryHierarchy] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=CategoryHierarchy, + ) + title: str = proto.Field( + proto.STRING, + number=3, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + item_attributes: common.FeatureMap = proto.Field( + proto.MESSAGE, + number=5, + message=common.FeatureMap, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + item_group_id: str = proto.Field( + proto.STRING, + number=9, + ) + product_metadata: 'ProductCatalogItem' = proto.Field( + proto.MESSAGE, + number=10, + oneof='recommendation_type', + message='ProductCatalogItem', + ) + + +class ProductCatalogItem(proto.Message): + r"""ProductCatalogItem captures item metadata specific to retail + 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: + exact_price (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.ExactPrice): + Optional. The exact product price. + + This field is a member of `oneof`_ ``price``. + price_range (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.PriceRange): + Optional. The product price range. + + This field is a member of `oneof`_ ``price``. + costs (MutableMapping[str, float]): + Optional. A map to pass the costs associated with the + product. + + For example: {"manufacturing": 45.5} The profit of selling + this item is computed like so: + + - If 'exactPrice' is provided, profit = displayPrice - + sum(costs) + - If 'priceRange' is provided, profit = minPrice - + sum(costs) + currency_code (str): + Optional. Only required if the price is set. + Currency code for price/costs. Use + three-character ISO-4217 code. + stock_state (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.StockState): + Optional. Online stock state of the catalog item. Default is + ``IN_STOCK``. + available_quantity (int): + Optional. The available quantity of the item. + canonical_product_uri (str): + Optional. Canonical URL directly linking to + the item detail page with a length limit of 5 + KiB.. + images (MutableSequence[google.cloud.recommendationengine_v1beta1.types.Image]): + Optional. Product images for the catalog + item. + """ + class StockState(proto.Enum): + r"""Item stock state. If this field is unspecified, the item is + assumed to be in stock. + + Values: + STOCK_STATE_UNSPECIFIED (0): + Default item stock status. Should never be + used. + IN_STOCK (0): + Item in stock. + OUT_OF_STOCK (1): + Item out of stock. + PREORDER (2): + Item that is in pre-order state. + BACKORDER (3): + Item that is back-ordered (i.e. temporarily + out of stock). + """ + _pb_options = {'allow_alias': True} + STOCK_STATE_UNSPECIFIED = 0 + IN_STOCK = 0 + OUT_OF_STOCK = 1 + PREORDER = 2 + BACKORDER = 3 + + class ExactPrice(proto.Message): + r"""Exact product price. + + Attributes: + display_price (float): + Optional. Display price of the product. + original_price (float): + Optional. Price of the product without any + discount. If zero, by default set to be the + 'displayPrice'. + """ + + display_price: float = proto.Field( + proto.FLOAT, + number=1, + ) + original_price: float = proto.Field( + proto.FLOAT, + number=2, + ) + + class PriceRange(proto.Message): + r"""Product price range when there are a range of prices for + different variations of the same product. + + Attributes: + min_ (float): + Required. The minimum product price. + max_ (float): + Required. The maximum product price. + """ + + min_: float = proto.Field( + proto.FLOAT, + number=1, + ) + max_: float = proto.Field( + proto.FLOAT, + number=2, + ) + + exact_price: ExactPrice = proto.Field( + proto.MESSAGE, + number=1, + oneof='price', + message=ExactPrice, + ) + price_range: PriceRange = proto.Field( + proto.MESSAGE, + number=2, + oneof='price', + message=PriceRange, + ) + costs: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.FLOAT, + number=3, + ) + currency_code: str = proto.Field( + proto.STRING, + number=4, + ) + stock_state: StockState = proto.Field( + proto.ENUM, + number=5, + enum=StockState, + ) + available_quantity: int = proto.Field( + proto.INT64, + number=6, + ) + canonical_product_uri: str = proto.Field( + proto.STRING, + number=7, + ) + images: MutableSequence['Image'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='Image', + ) + + +class Image(proto.Message): + r"""Catalog item thumbnail/detail image. + + Attributes: + uri (str): + Required. URL of the image with a length + limit of 5 KiB. + height (int): + Optional. Height of the image in number of + pixels. + width (int): + Optional. Width of the image in number of + pixels. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + height: int = proto.Field( + proto.INT32, + number=2, + ) + width: int = proto.Field( + proto.INT32, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py new file mode 100644 index 00000000..1908345e --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/catalog_service.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'CreateCatalogItemRequest', + 'GetCatalogItemRequest', + 'ListCatalogItemsRequest', + 'ListCatalogItemsResponse', + 'UpdateCatalogItemRequest', + 'DeleteCatalogItemRequest', + }, +) + + +class CreateCatalogItemRequest(proto.Message): + r"""Request message for CreateCatalogItem method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): + Required. The catalog item to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + catalog_item: catalog.CatalogItem = proto.Field( + proto.MESSAGE, + number=2, + message=catalog.CatalogItem, + ) + + +class GetCatalogItemRequest(proto.Message): + r"""Request message for GetCatalogItem method. + + Attributes: + name (str): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_id``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListCatalogItemsRequest(proto.Message): + r"""Request message for ListCatalogItems method. + + Attributes: + parent (str): + Required. The parent catalog resource name, such as + ``projects/*/locations/global/catalogs/default_catalog``. + page_size (int): + Optional. Maximum number of results to return + per page. If zero, the service will choose a + reasonable default. + page_token (str): + Optional. The previous + ListCatalogItemsResponse.next_page_token. + filter (str): + Optional. A filter to apply on the list + results. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListCatalogItemsResponse(proto.Message): + r"""Response message for ListCatalogItems method. + + Attributes: + catalog_items (MutableSequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem]): + The catalog items. + next_page_token (str): + If empty, the list is complete. If nonempty, the token to + pass to the next request's + ListCatalogItemRequest.page_token. + """ + + @property + def raw_page(self): + return self + + catalog_items: MutableSequence[catalog.CatalogItem] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=catalog.CatalogItem, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCatalogItemRequest(proto.Message): + r"""Request message for UpdateCatalogItem method. + + Attributes: + name (str): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id``. + catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): + Required. The catalog item to update/create. The + 'catalog_item_id' field has to match that in the 'name'. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Indicates which fields in the + provided 'item' to update. If not set, will by + default update all fields. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + catalog_item: catalog.CatalogItem = proto.Field( + proto.MESSAGE, + number=2, + message=catalog.CatalogItem, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteCatalogItemRequest(proto.Message): + r"""Request message for DeleteCatalogItem method. + + Attributes: + name (str): + Required. Full resource name of catalog item, such as + ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py new file mode 100644 index 00000000..abf31f86 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/common.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'FeatureMap', + }, +) + + +class FeatureMap(proto.Message): + r"""FeatureMap represents extra features that customers want to + include in the recommendation model for catalogs/user events as + categorical/numerical features. + + Attributes: + categorical_features (MutableMapping[str, google.cloud.recommendationengine_v1beta1.types.FeatureMap.StringList]): + Categorical features that can take on one of a limited + number of possible values. Some examples would be the + brand/maker of a product, or country of a customer. + + Feature names and values must be UTF-8 encoded strings. + + For example: + ``{ "colors": {"value": ["yellow", "green"]}, "sizes": {"value":["S", "M"]}`` + numerical_features (MutableMapping[str, google.cloud.recommendationengine_v1beta1.types.FeatureMap.FloatList]): + Numerical features. Some examples would be the height/weight + of a product, or age of a customer. + + Feature names must be UTF-8 encoded strings. + + For example: + ``{ "lengths_cm": {"value":[2.3, 15.4]}, "heights_cm": {"value":[8.1, 6.4]} }`` + """ + + class StringList(proto.Message): + r"""A list of string features. + + Attributes: + value (MutableSequence[str]): + String feature value with a length limit of + 128 bytes. + """ + + value: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class FloatList(proto.Message): + r"""A list of float features. + + Attributes: + value (MutableSequence[float]): + Float feature value. + """ + + value: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=1, + ) + + categorical_features: MutableMapping[str, StringList] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=StringList, + ) + numerical_features: MutableMapping[str, FloatList] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=FloatList, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py new file mode 100644 index 00000000..7d74cd6a --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/import_.py @@ -0,0 +1,398 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import user_event +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'GcsSource', + 'CatalogInlineSource', + 'UserEventInlineSource', + 'ImportErrorsConfig', + 'ImportCatalogItemsRequest', + 'ImportUserEventsRequest', + 'InputConfig', + 'ImportMetadata', + 'ImportCatalogItemsResponse', + 'ImportUserEventsResponse', + 'UserEventImportSummary', + }, +) + + +class GcsSource(proto.Message): + r"""Google Cloud Storage location for input content. + format. + + Attributes: + input_uris (MutableSequence[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 catalog + information `__ for + the expected file format and setup instructions. + """ + + input_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class CatalogInlineSource(proto.Message): + r"""The inline source for the input config for ImportCatalogItems + method. + + Attributes: + catalog_items (MutableSequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem]): + Optional. A list of catalog items to + update/create. Recommended max of 10k items. + """ + + catalog_items: MutableSequence[catalog.CatalogItem] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=catalog.CatalogItem, + ) + + +class UserEventInlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (MutableSequence[google.cloud.recommendationengine_v1beta1.types.UserEvent]): + Optional. A list of user events to import. + Recommended max of 10k items. + """ + + user_events: MutableSequence[user_event.UserEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + +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 path for import errors. This must be an + empty, existing Cloud Storage bucket. Import 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: str = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportCatalogItemsRequest(proto.Message): + r"""Request message for Import methods. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog`` + request_id (str): + Optional. Unique identifier provided by + client, within the ancestor dataset scope. + Ensures idempotency and used for request + deduplication. Server-generated if unspecified. + Up to 128 characters long. This is returned as + google.longrunning.Operation.name in the + response. + input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Optional. The desired location of errors + incurred during the Import. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + input_config: 'InputConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='InputConfig', + ) + errors_config: 'ImportErrorsConfig' = proto.Field( + proto.MESSAGE, + number=4, + message='ImportErrorsConfig', + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + Attributes: + parent (str): + Required. + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + request_id (str): + Optional. Unique identifier provided by client, within the + ancestor dataset scope. Ensures idempotency for expensive + long running operations. Server-generated if unspecified. Up + to 128 characters long. This is returned as + google.longrunning.Operation.name in the response. Note that + this field must not be set if the desired input config is + catalog_inline_source. + input_config (google.cloud.recommendationengine_v1beta1.types.InputConfig): + Required. The desired input location of the + data. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Optional. The desired location of errors + incurred during the Import. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + input_config: 'InputConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='InputConfig', + ) + errors_config: 'ImportErrorsConfig' = proto.Field( + proto.MESSAGE, + number=4, + message='ImportErrorsConfig', + ) + + +class InputConfig(proto.Message): + r"""The input config source. + + 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: + catalog_inline_source (google.cloud.recommendationengine_v1beta1.types.CatalogInlineSource): + The Inline source for the input content for + Catalog items. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.recommendationengine_v1beta1.types.GcsSource): + Google Cloud Storage location for the input + content. + + This field is a member of `oneof`_ ``source``. + user_event_inline_source (google.cloud.recommendationengine_v1beta1.types.UserEventInlineSource): + The Inline source for the input content for + UserEvents. + + This field is a member of `oneof`_ ``source``. + """ + + catalog_inline_source: 'CatalogInlineSource' = proto.Field( + proto.MESSAGE, + number=1, + oneof='source', + message='CatalogInlineSource', + ) + gcs_source: 'GcsSource' = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GcsSource', + ) + user_event_inline_source: 'UserEventInlineSource' = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='UserEventInlineSource', + ) + + +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: + operation_name (str): + Name of the operation. + request_id (str): + Id of the request / operation. This is + parroting back the requestId that was passed in + the request. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + operation_name: str = proto.Field( + proto.STRING, + number=5, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=1, + ) + failure_count: int = proto.Field( + proto.INT64, + number=2, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class ImportCatalogItemsResponse(proto.Message): + r"""Response of the ImportCatalogItemsRequest. If the long + running operation is done, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config: 'ImportErrorsConfig' = 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 (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + errors_config (google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig): + Echoes the destination for the complete + errors if this field was set in the request. + import_summary (google.cloud.recommendationengine_v1beta1.types.UserEventImportSummary): + Aggregated statistics of user event import + status. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + errors_config: 'ImportErrorsConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorsConfig', + ) + import_summary: 'UserEventImportSummary' = 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: int = proto.Field( + proto.INT64, + number=1, + ) + unjoined_events_count: int = proto.Field( + proto.INT64, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py new file mode 100644 index 00000000..c3578f63 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'PredictionApiKeyRegistration', + 'CreatePredictionApiKeyRegistrationRequest', + 'ListPredictionApiKeyRegistrationsRequest', + 'ListPredictionApiKeyRegistrationsResponse', + 'DeletePredictionApiKeyRegistrationRequest', + }, +) + + +class PredictionApiKeyRegistration(proto.Message): + r"""Registered Api Key. + + Attributes: + api_key (str): + The API key. + """ + + api_key: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreatePredictionApiKeyRegistrationRequest(proto.Message): + r"""Request message for the ``CreatePredictionApiKeyRegistration`` + method. + + Attributes: + parent (str): + Required. The parent resource path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + prediction_api_key_registration (google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration): + Required. The prediction API key + registration. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + prediction_api_key_registration: 'PredictionApiKeyRegistration' = proto.Field( + proto.MESSAGE, + number=2, + message='PredictionApiKeyRegistration', + ) + + +class ListPredictionApiKeyRegistrationsRequest(proto.Message): + r"""Request message for the ``ListPredictionApiKeyRegistrations``. + + Attributes: + parent (str): + Required. The parent placement resource name such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + page_size (int): + Optional. Maximum number of results to return + per page. If unset, the service will choose a + reasonable default. + page_token (str): + Optional. The previous + ``ListPredictionApiKeyRegistration.nextPageToken``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPredictionApiKeyRegistrationsResponse(proto.Message): + r"""Response message for the ``ListPredictionApiKeyRegistrations``. + + Attributes: + prediction_api_key_registrations (MutableSequence[google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration]): + The list of registered API keys. + next_page_token (str): + If empty, the list is complete. If nonempty, pass the token + to the next request's + ``ListPredictionApiKeysRegistrationsRequest.pageToken``. + """ + + @property + def raw_page(self): + return self + + prediction_api_key_registrations: MutableSequence['PredictionApiKeyRegistration'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='PredictionApiKeyRegistration', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeletePredictionApiKeyRegistrationRequest(proto.Message): + r"""Request message for ``DeletePredictionApiKeyRegistration`` method. + + Attributes: + name (str): + Required. The API key to unregister including full resource + path. + ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py new file mode 100644 index 00000000..0b39a774 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/prediction_service.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'PredictRequest', + 'PredictResponse', + }, +) + + +class PredictRequest(proto.Message): + r"""Request message for Predict method. + + Attributes: + name (str): + Required. Full resource name of the format: + ``{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`` + The id of the recommendation engine placement. This id is + used to identify the set of models that will be used to make + the prediction. + + We currently support three placements with the following IDs + by default: + + - ``shopping_cart``: Predicts items frequently bought + together with one or more catalog items in the same + shopping session. Commonly displayed after + ``add-to-cart`` events, on product detail pages, or on + the shopping cart page. + + - ``home_page``: Predicts the next product that a user will + most likely engage with or purchase based on the shopping + or viewing history of the specified ``userId`` or + ``visitorId``. For example - Recommendations for you. + + - ``product_detail``: Predicts the next product that a user + will most likely engage with or purchase. The prediction + is based on the shopping or viewing history of the + specified ``userId`` or ``visitorId`` and its relevance + to a specified ``CatalogItem``. Typically used on product + detail pages. For example - More items like this. + + - ``recently_viewed_default``: Returns up to 75 items + recently viewed by the specified ``userId`` or + ``visitorId``, most recent ones first. Returns nothing if + neither of them has viewed any items yet. For example - + Recently viewed. + + The full list of available placements can be seen at + https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard + user_event (google.cloud.recommendationengine_v1beta1.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): + Optional. Maximum number of results to return + per page. Set this property to the number of + prediction results required. If zero, the + service will choose a reasonable default. + page_token (str): + Optional. The previous PredictResponse.next_page_token. + filter (str): + Optional. Filter for restricting prediction results. Accepts + values for tags and the ``filterOutOfStockItems`` flag. + + - Tag expressions. Restricts predictions to items 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 KiB. + + - filterOutOfStockItems. Restricts predictions to items + 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 + dry_run (bool): + Optional. Use dryRun mode for this prediction + query. If set to true, a dummy model will be + used that returns arbitrary catalog items. Note + that the dryRun mode should only be used for + testing the API, or if the model is not ready. + params (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Optional. Additional domain specific parameters for the + predictions. + + Allowed values: + + - ``returnCatalogItem``: Boolean. If set to true, the + associated catalogItem object will be returned in the + ``PredictResponse.PredictionResult.itemMetadata`` object + in the method response. + - ``returnItemScore``: Boolean. If set to true, the + prediction 'score' corresponding to each returned item + will be set in the ``metadata`` field in the prediction + response. The given 'score' indicates the probability of + an item being clicked/purchased given the user's context + and history. + labels (MutableMapping[str, str]): + Optional. The labels for the predict request. + + - Label keys can contain lowercase letters, digits and + hyphens, must start with a letter, and must end with a + letter or digit. + - Non-zero label values can contain lowercase letters, + digits and hyphens, must start with a letter, and must + end with a letter or digit. + - No more than 64 labels can be associated with a given + request. + + See https://goo.gl/xmQnxf for more information on and + examples of labels. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: gcr_user_event.UserEvent = proto.Field( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + page_size: int = proto.Field( + proto.INT32, + number=7, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + dry_run: bool = proto.Field( + proto.BOOL, + number=4, + ) + params: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=6, + message=struct_pb2.Value, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) + + +class PredictResponse(proto.Message): + r"""Response message for predict method. + + Attributes: + results (MutableSequence[google.cloud.recommendationengine_v1beta1.types.PredictResponse.PredictionResult]): + A list of recommended items. The order + represents the ranking (from the most relevant + item to the least). + recommendation_token (str): + A unique recommendation token. This should be + included in the user event logs resulting from + this recommendation, which enables accurate + attribution of recommendation model performance. + items_missing_in_catalog (MutableSequence[str]): + IDs of items in the request that were missing + from the catalog. + dry_run (bool): + True if the dryRun property was set in the + request. + metadata (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific prediction + response metadata. + next_page_token (str): + If empty, the list is complete. If nonempty, the token to + pass to the next request's PredictRequest.page_token. + """ + + class PredictionResult(proto.Message): + r"""PredictionResult represents the recommendation prediction + results. + + Attributes: + id (str): + ID of the recommended catalog item + item_metadata (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional item metadata / annotations. + + Possible values: + + - ``catalogItem``: JSON representation of the catalogItem. + Will be set if ``returnCatalogItem`` is set to true in + ``PredictRequest.params``. + - ``score``: Prediction score in double value. Will be set + if ``returnItemScore`` is set to true in + ``PredictRequest.params``. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + item_metadata: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + @property + def raw_page(self): + return self + + results: MutableSequence[PredictionResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=PredictionResult, + ) + recommendation_token: str = proto.Field( + proto.STRING, + number=2, + ) + items_missing_in_catalog: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + dry_run: bool = proto.Field( + proto.BOOL, + number=4, + ) + metadata: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py new file mode 100644 index 00000000..3e000be1 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF 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.recommendationengine.v1beta1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py new file mode 100644 index 00000000..afc1b91f --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event.py @@ -0,0 +1,536 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import common +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'UserEvent', + 'UserInfo', + 'EventDetail', + 'ProductEventDetail', + 'PurchaseTransaction', + 'ProductDetail', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information recommendation + engine 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. + - ``add-to-list`` Items being added to a list (shopping + list, favorites etc). + - ``category-page-view`` Special pages such as sale or + promotion pages viewed. + - ``checkout-start`` User starting a checkout process. + - ``detail-page-view`` Products detail page viewed. + - ``home-page-view`` Homepage viewed. + - ``page-visit`` Generic page visits not included in the + event types above. + - ``purchase-complete`` User finishing a purchase. + - ``refund`` Purchased items being refunded or returned. + - ``remove-from-cart`` Products being removed from cart. + - ``remove-from-list`` Items being removed from a list. + - ``search`` Product search. + - ``shopping-cart-page-view`` User viewing a shopping cart. + - ``impression`` List of items displayed. Used by Google + Tag Manager. + user_info (google.cloud.recommendationengine_v1beta1.types.UserInfo): + Required. User information. + event_detail (google.cloud.recommendationengine_v1beta1.types.EventDetail): + Optional. User event detailed information + common across different recommendation types. + product_event_detail (google.cloud.recommendationengine_v1beta1.types.ProductEventDetail): + Optional. Retail product specific user event metadata. + + This field is required for the following event types: + + - ``add-to-cart`` + - ``add-to-list`` + - ``category-page-view`` + - ``checkout-start`` + - ``detail-page-view`` + - ``purchase-complete`` + - ``refund`` + - ``remove-from-cart`` + - ``remove-from-list`` + - ``search`` + + This field is optional for the following event types: + + - ``page-visit`` + - ``shopping-cart-page-view`` - note that + 'product_event_detail' should be set for this unless the + shopping cart is empty. + + This field is not allowed for the following event types: + + - ``home-page-view`` + event_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Only required for ImportUserEvents + method. Timestamp of user event created. + event_source (google.cloud.recommendationengine_v1beta1.types.UserEvent.EventSource): + Optional. This field should *not* be set when using + JavaScript pixel or the Recommendations AI Tag. Defaults to + ``EVENT_SOURCE_UNSPECIFIED``. + """ + class EventSource(proto.Enum): + r"""User event source. + + Values: + EVENT_SOURCE_UNSPECIFIED (0): + Unspecified event source. + AUTOML (1): + The event is ingested via a javascript pixel + or Recommendations AI Tag through automl + datalayer or JS Macros. + ECOMMERCE (2): + The event is ingested via Recommendations AI + Tag through Enhanced Ecommerce datalayer. + BATCH_UPLOAD (3): + The event is ingested via Import user events + API. + """ + EVENT_SOURCE_UNSPECIFIED = 0 + AUTOML = 1 + ECOMMERCE = 2 + BATCH_UPLOAD = 3 + + event_type: str = proto.Field( + proto.STRING, + number=1, + ) + user_info: 'UserInfo' = proto.Field( + proto.MESSAGE, + number=2, + message='UserInfo', + ) + event_detail: 'EventDetail' = proto.Field( + proto.MESSAGE, + number=3, + message='EventDetail', + ) + product_event_detail: 'ProductEventDetail' = proto.Field( + proto.MESSAGE, + number=4, + message='ProductEventDetail', + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + event_source: EventSource = proto.Field( + proto.ENUM, + number=6, + enum=EventSource, + ) + + +class UserInfo(proto.Message): + r"""Information of end users. + + Attributes: + visitor_id (str): + Required. A unique identifier for tracking + visitors with a length limit of 128 bytes. + + For example, this could be implemented with a + 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. Maximum + length 128 bytes. Cannot be empty. + user_id (str): + Optional. Unique identifier for logged-in + user with a length limit of 128 bytes. Required + only for logged-in users. + ip_address (str): + Optional. IP address of the user. This could be either IPv4 + (e.g. 104.133.9.80) or IPv6 (e.g. + 2001:0db8:85a3:0000:0000:8a2e:0370:7334). This should *not* + be set when using the javascript pixel or if + ``direct_user_request`` is set. Used to extract location + information for personalization. + user_agent (str): + Optional. User agent as included in the HTTP header. UTF-8 + encoded string with a length limit of 1 KiB. + + This should *not* be set when using the JavaScript pixel or + if ``directUserRequest`` is set. + direct_user_request (bool): + Optional. Indicates if the request is made directly from the + end user in which case the user_agent and ip_address fields + can be populated from the HTTP request. This should *not* be + set when using the javascript pixel. 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). + """ + + visitor_id: str = proto.Field( + proto.STRING, + number=1, + ) + user_id: str = proto.Field( + proto.STRING, + number=2, + ) + ip_address: str = proto.Field( + proto.STRING, + number=3, + ) + user_agent: str = proto.Field( + proto.STRING, + number=4, + ) + direct_user_request: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class EventDetail(proto.Message): + r"""User event details shared by all recommendation types. + + Attributes: + uri (str): + Optional. Complete url (window.location.href) + of the user's current page. When using the + JavaScript pixel, this value is filled in + automatically. Maximum length 5KB. + referrer_uri (str): + Optional. The referrer url of the current + page. When using the JavaScript pixel, this + value is filled in automatically. + page_view_id (str): + Optional. 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. + This ``pageViewId`` will be automatically generated if using + the JavaScript pixel. + experiment_ids (MutableSequence[str]): + Optional. 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 Recommendation Engine system, + using different recommendation models). + recommendation_token (str): + Optional. Recommendation token included in the + recommendation prediction response. + + This field enables accurate attribution of recommendation + model performance. + + This token enables us to accurately attribute page view or + purchase back to the event and the particular predict + response containing this clicked/purchased item. If user + clicks on product K in the recommendation results, pass the + ``PredictResponse.recommendationToken`` property as a url + parameter to product K's page. When recording events on + product K's page, log the + PredictResponse.recommendation_token to this field. + + Optional, but highly encouraged for user events that are the + result of a recommendation prediction query. + event_attributes (google.cloud.recommendationengine_v1beta1.types.FeatureMap): + Optional. Extra user event features to include in the + recommendation model. + + For product recommendation, an example of extra user + information is traffic_channel, i.e. how user arrives at the + site. Users can arrive at the site by coming to the site + directly, or coming through Google search, and etc. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + referrer_uri: str = proto.Field( + proto.STRING, + number=6, + ) + page_view_id: str = proto.Field( + proto.STRING, + number=2, + ) + experiment_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + recommendation_token: str = proto.Field( + proto.STRING, + number=4, + ) + event_attributes: common.FeatureMap = proto.Field( + proto.MESSAGE, + number=5, + message=common.FeatureMap, + ) + + +class ProductEventDetail(proto.Message): + r"""ProductEventDetail captures user event information specific + to retail products. + + Attributes: + search_query (str): + Required for ``search`` events. Other event types should not + set this field. The user's search query as UTF-8 encoded + text with a length limit of 5 KiB. + page_categories (MutableSequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem.CategoryHierarchy]): + Required for ``category-page-view`` events. Other event + types should not set this field. The categories associated + with a category page. Category pages include special pages + such as sales or promotions. For instance, a special sale + page may have the category hierarchy: categories : ["Sales", + "2017 Black Friday Deals"]. + product_details (MutableSequence[google.cloud.recommendationengine_v1beta1.types.ProductDetail]): + The main product details related to the event. + + This field is required for the following event types: + + - ``add-to-cart`` + - ``add-to-list`` + - ``checkout-start`` + - ``detail-page-view`` + - ``purchase-complete`` + - ``refund`` + - ``remove-from-cart`` + - ``remove-from-list`` + + This field is optional for the following event types: + + - ``page-visit`` + - ``shopping-cart-page-view`` - note that 'product_details' + should be set for this unless the shopping cart is empty. + + This field is not allowed for the following event types: + + - ``category-page-view`` + - ``home-page-view`` + - ``search`` + list_id (str): + Required for ``add-to-list`` and ``remove-from-list`` + events. The id or name of the list that the item is being + added to or removed from. Other event types should not set + this field. + cart_id (str): + Optional. 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``, + ``remove-from-cart``, ``checkout-start``, + ``purchase-complete``, or ``shopping-cart-page-view`` + events. + purchase_transaction (google.cloud.recommendationengine_v1beta1.types.PurchaseTransaction): + Optional. A transaction represents the entire purchase + transaction. Required for ``purchase-complete`` events. + Optional for ``checkout-start`` events. Other event types + should not set this field. + """ + + search_query: str = proto.Field( + proto.STRING, + number=1, + ) + page_categories: MutableSequence[catalog.CatalogItem.CategoryHierarchy] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=catalog.CatalogItem.CategoryHierarchy, + ) + product_details: MutableSequence['ProductDetail'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='ProductDetail', + ) + list_id: str = proto.Field( + proto.STRING, + number=4, + ) + cart_id: str = proto.Field( + proto.STRING, + number=5, + ) + purchase_transaction: 'PurchaseTransaction' = proto.Field( + proto.MESSAGE, + number=6, + message='PurchaseTransaction', + ) + + +class PurchaseTransaction(proto.Message): + r"""A transaction represents the entire purchase transaction. + + Attributes: + id (str): + Optional. The transaction ID with a length + limit of 128 bytes. + revenue (float): + Required. Total 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. This field is not + required if the event type is ``refund``. + taxes (MutableMapping[str, float]): + Optional. All the taxes associated with the + transaction. + costs (MutableMapping[str, float]): + Optional. All the costs associated with the product. These + can be manufacturing costs, shipping expenses not borne by + the end user, or any other costs. + + Total product cost such that profit = revenue - (sum(taxes) + + sum(costs)) If product_cost is not set, then profit = + revenue - tax - shipping - sum(CatalogItem.costs). + + If CatalogItem.cost is not specified for one of the items, + CatalogItem.cost based profit *cannot* be calculated for + this Transaction. + currency_code (str): + Required. Currency code. Use three-character ISO-4217 code. + This field is not required if the event type is ``refund``. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + revenue: float = proto.Field( + proto.FLOAT, + number=2, + ) + taxes: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.FLOAT, + number=3, + ) + costs: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.FLOAT, + number=4, + ) + currency_code: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ProductDetail(proto.Message): + r"""Detailed product information associated with a user event. + + Attributes: + id (str): + Required. Catalog item ID. UTF-8 encoded + string with a length limit of 128 characters. + currency_code (str): + Optional. Currency code for price/costs. Use + three-character ISO-4217 code. Required only if + originalPrice or displayPrice is set. + original_price (float): + Optional. Original price of the product. If + provided, this will override the original price + in Catalog for this product. + display_price (float): + Optional. Display price of the product (e.g. + discounted price). If provided, this will + override the display price in Catalog for this + product. + stock_state (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.StockState): + Optional. Item stock state. If provided, this + overrides the stock state in Catalog for items + in this event. + quantity (int): + Optional. 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 ``add-to-cart`` event. + Required for ``add-to-cart``, ``add-to-list``, + ``remove-from-cart``, ``checkout-start``, + ``purchase-complete``, ``refund`` event types. + available_quantity (int): + Optional. Quantity of the products in stock when a user + event happens. Optional. If provided, this overrides the + available quantity in Catalog for this event. and can only + be set if ``stock_status`` is set to ``IN_STOCK``. + + Note that if an item is out of stock, you must set the + ``stock_state`` field to be ``OUT_OF_STOCK``. Leaving this + field unspecified / as zero is not sufficient to mark the + item out of stock. + item_attributes (google.cloud.recommendationengine_v1beta1.types.FeatureMap): + Optional. Extra features associated with a + product in the user event. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + currency_code: str = proto.Field( + proto.STRING, + number=2, + ) + original_price: float = proto.Field( + proto.FLOAT, + number=3, + ) + display_price: float = proto.Field( + proto.FLOAT, + number=4, + ) + stock_state: catalog.ProductCatalogItem.StockState = proto.Field( + proto.ENUM, + number=5, + enum=catalog.ProductCatalogItem.StockState, + ) + quantity: int = proto.Field( + proto.INT32, + number=6, + ) + available_quantity: int = proto.Field( + proto.INT32, + number=7, + ) + item_attributes: common.FeatureMap = proto.Field( + proto.MESSAGE, + number=8, + message=common.FeatureMap, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py new file mode 100644 index 00000000..e02ca97f --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/recommendationengine_v1beta1/types/user_event_service.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.recommendationengine.v1beta1', + manifest={ + 'PurgeUserEventsRequest', + 'PurgeUserEventsMetadata', + 'PurgeUserEventsResponse', + 'WriteUserEventRequest', + 'CollectUserEventRequest', + 'ListUserEventsRequest', + 'ListUserEventsResponse', + }, +) + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the event_store under which + the events are created. The format is + ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` + filter (str): + Required. The filter string to specify the events to be + deleted. Empty string filter is not allowed. This filter can + also be used with ListUserEvents API to list events that + will be deleted. The eligible fields for filtering are: + + - eventType - UserEvent.eventType field of type string. + - eventTime - in ISO 8601 "zulu" format. + - visitorId - field of type string. Specifying this will + delete all events associated with a visitor. + - userId - field of type string. Specifying this will + delete all events associated with a user. Example 1: + Deleting all events in a time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + Example 2: Deleting specific eventType in time range. + ``eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`` + Example 3: Deleting all events for a specific visitor + ``visitorId = visitor1024`` The filtering fields are + assumed to have an implicit AND. + force (bool): + Optional. The default value is false. + Override this flag to true to actually perform + the purge. If the field is not set to true, a + sampling of events to be deleted will be + returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsMetadata(proto.Message): + r"""Metadata related to the progress of the PurgeUserEvents + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + operation_name (str): + The ID of the request / operation. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + """ + + operation_name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +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. + user_events_sample (MutableSequence[google.cloud.recommendationengine_v1beta1.types.UserEvent]): + A sampling of events deleted (or will be deleted) depending + on the ``force`` property in the request. Max of 500 items + will be returned. + """ + + purged_events_count: int = proto.Field( + proto.INT64, + number=1, + ) + user_events_sample: MutableSequence[gcr_user_event.UserEvent] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gcr_user_event.UserEvent, + ) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + Attributes: + parent (str): + Required. The parent eventStore resource name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + user_event (google.cloud.recommendationengine_v1beta1.types.UserEvent): + Required. User event to write. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: gcr_user_event.UserEvent = 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 eventStore name, such as + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. + user_event (str): + Required. URL encoded UserEvent proto. + uri (str): + Optional. The url including cgi-parameters + but excluding the hash fragment. The URL must be + truncated to 1.5K bytes to conservatively be + under the 2K bytes. This is often more useful + than the referer url, because many browsers only + send the domain for 3rd party requests. + ets (int): + Optional. The event timestamp in + milliseconds. This prevents browser caching of + otherwise identical get requests. The name is + abbreviated to reduce the payload bytes. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + ) + ets: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ListUserEventsRequest(proto.Message): + r"""Request message for ListUserEvents method. + + Attributes: + parent (str): + Required. The parent eventStore resource name, such as + ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store``. + page_size (int): + Optional. Maximum number of results to return + per page. If zero, the service will choose a + reasonable default. + page_token (str): + Optional. The previous + ListUserEventsResponse.next_page_token. + filter (str): + Optional. Filtering expression to specify restrictions over + returned events. This is a sequence of terms, where each + term applies some kind of a restriction to the returned user + events. Use this expression to restrict results to a + specific time range, or filter events by eventType. eg: + eventTime > "2012-04-23T18:25:43.511Z" + eventsMissingCatalogItems + eventTime<"2012-04-23T18:25:43.511Z" eventType=search + + We expect only 3 types of fields: + + :: + + * eventTime: this can be specified a maximum of 2 times, once with a + less than operator and once with a greater than operator. The + eventTime restrict should result in one contiguous valid eventTime + range. + + * eventType: only 1 eventType restriction can be specified. + + * eventsMissingCatalogItems: specififying this will restrict results + to events for which catalog items were not found in the catalog. The + default behavior is to return only those events for which catalog + items were found. + + Some examples of valid filters expressions: + + - Example 1: eventTime > "2012-04-23T18:25:43.511Z" + eventTime < "2012-04-23T18:30:43.511Z" + - Example 2: eventTime > "2012-04-23T18:25:43.511Z" + eventType = detail-page-view + - Example 3: eventsMissingCatalogItems eventType = search + eventTime < "2018-04-23T18:30:43.511Z" + - Example 4: eventTime > "2012-04-23T18:25:43.511Z" + - Example 5: eventType = search + - Example 6: eventsMissingCatalogItems + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListUserEventsResponse(proto.Message): + r"""Response message for ListUserEvents method. + + Attributes: + user_events (MutableSequence[google.cloud.recommendationengine_v1beta1.types.UserEvent]): + The user events. + next_page_token (str): + If empty, the list is complete. If nonempty, the token to + pass to the next request's ListUserEvents.page_token. + """ + + @property + def raw_page(self): + return self + + user_events: MutableSequence[gcr_user_event.UserEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcr_user_event.UserEvent, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini new file mode 100644 index 00000000..574c5aed --- /dev/null +++ b/owl-bot-staging/v1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py new file mode 100644 index 00000000..72655638 --- /dev/null +++ b/owl-bot-staging/v1beta1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/recommendationengine_v1beta1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_async.py new file mode 100644 index 00000000..e1310b62 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_create_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value1', 'categories_value2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.CreateCatalogItemRequest( + parent="parent_value", + catalog_item=catalog_item, + ) + + # Make the request + response = await client.create_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_sync.py new file mode 100644 index 00000000..53f10713 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_create_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value1', 'categories_value2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.CreateCatalogItemRequest( + parent="parent_value", + catalog_item=catalog_item, + ) + + # Make the request + response = client.create_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_async.py new file mode 100644 index 00000000..850f6c01 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_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 DeleteCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_delete_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeleteCatalogItemRequest( + name="name_value", + ) + + # Make the request + await client.delete_catalog_item(request=request) + + +# [END recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_sync.py new file mode 100644 index 00000000..849c9429 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_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 DeleteCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_delete_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeleteCatalogItemRequest( + name="name_value", + ) + + # Make the request + client.delete_catalog_item(request=request) + + +# [END recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_async.py new file mode 100644 index 00000000..523b166c --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_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 GetCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_get_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.GetCatalogItemRequest( + name="name_value", + ) + + # Make the request + response = await client.get_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_sync.py new file mode 100644 index 00000000..770e0679 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_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 GetCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_get_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.GetCatalogItemRequest( + name="name_value", + ) + + # Make the request + response = client.get_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_async.py new file mode 100644 index 00000000..d8572aa7 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCatalogItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_import_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_catalog_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_sync.py new file mode 100644 index 00000000..6091ccc0 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCatalogItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_import_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_catalog_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_async.py new file mode 100644 index 00000000..0c04997e --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_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 ListCatalogItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_list_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalog_items(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_sync.py new file mode 100644 index 00000000..ca082bfd --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_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 ListCatalogItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_list_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalog_items(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_async.py new file mode 100644 index 00000000..1c1cc93f --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_update_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value1', 'categories_value2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.UpdateCatalogItemRequest( + name="name_value", + catalog_item=catalog_item, + ) + + # Make the request + response = await client.update_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_sync.py new file mode 100644 index 00000000..e3699cbd --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_update_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value1', 'categories_value2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.UpdateCatalogItemRequest( + name="name_value", + catalog_item=catalog_item, + ) + + # Make the request + response = client.update_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_async.py new file mode 100644 index 00000000..30217d47 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_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 CreatePredictionApiKeyRegistration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_create_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CreatePredictionApiKeyRegistrationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_prediction_api_key_registration(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_sync.py new file mode 100644 index 00000000..f49cae82 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_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 CreatePredictionApiKeyRegistration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_create_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CreatePredictionApiKeyRegistrationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_prediction_api_key_registration(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_async.py new file mode 100644 index 00000000..83b7fe64 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_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 DeletePredictionApiKeyRegistration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_delete_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeletePredictionApiKeyRegistrationRequest( + name="name_value", + ) + + # Make the request + await client.delete_prediction_api_key_registration(request=request) + + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_sync.py new file mode 100644 index 00000000..21860810 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_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 DeletePredictionApiKeyRegistration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_delete_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeletePredictionApiKeyRegistrationRequest( + name="name_value", + ) + + # Make the request + client.delete_prediction_api_key_registration(request=request) + + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_async.py new file mode 100644 index 00000000..08b737a9 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_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 ListPredictionApiKeyRegistrations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_list_prediction_api_key_registrations(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListPredictionApiKeyRegistrationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_prediction_api_key_registrations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_sync.py new file mode 100644 index 00000000..fca8f902 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_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 ListPredictionApiKeyRegistrations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_list_prediction_api_key_registrations(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListPredictionApiKeyRegistrationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_prediction_api_key_registrations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_async.py new file mode 100644 index 00000000..4f4ba0a7 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionService_Predict_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_predict(): + # Create a client + client = recommendationengine_v1beta1.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.PredictRequest( + name="name_value", + user_event=user_event, + ) + + # Make the request + page_result = client.predict(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionService_Predict_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_sync.py new file mode 100644 index 00000000..1f9ddd35 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionService_Predict_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_predict(): + # Create a client + client = recommendationengine_v1beta1.PredictionServiceClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.PredictRequest( + name="name_value", + user_event=user_event, + ) + + # Make the request + page_result = client.predict(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionService_Predict_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 00000000..6e440f1b --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_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 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-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_collect_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.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 recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 00000000..5ba6c4e7 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_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 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-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_collect_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.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 recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_async.py new file mode 100644 index 00000000..ed7bfd23 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_import_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 00000000..00537a62 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_import_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_async.py new file mode 100644 index 00000000..3c770752 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_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 ListUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_list_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListUserEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_sync.py new file mode 100644 index 00000000..bf8be483 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_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 ListUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_list_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListUserEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_events(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 00000000..f4de6402 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_purge_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.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 recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 00000000..76e415f4 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_purge_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.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 recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_async.py new file mode 100644 index 00000000..7583b085 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +async def sample_write_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.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 recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 00000000..42ffae37 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import recommendationengine_v1beta1 + + +def sample_write_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.recommendationengine.v1beta1.json b/owl-bot-staging/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.recommendationengine.v1beta1.json new file mode 100644 index 00000000..8cfa1979 --- /dev/null +++ b/owl-bot-staging/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.recommendationengine.v1beta1.json @@ -0,0 +1,2570 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.recommendationengine.v1beta1", + "version": "v1beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-recommendations-ai", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient.create_catalog_item", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.CreateCatalogItem", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "CreateCatalogItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.CreateCatalogItemRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "catalog_item", + "type": "google.cloud.recommendationengine_v1beta1.types.CatalogItem" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.types.CatalogItem", + "shortName": "create_catalog_item" + }, + "description": "Sample for CreateCatalogItem", + "file": "recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient.create_catalog_item", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.CreateCatalogItem", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "CreateCatalogItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.CreateCatalogItemRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "catalog_item", + "type": "google.cloud.recommendationengine_v1beta1.types.CatalogItem" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.types.CatalogItem", + "shortName": "create_catalog_item" + }, + "description": "Sample for CreateCatalogItem", + "file": "recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient.delete_catalog_item", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.DeleteCatalogItem", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "DeleteCatalogItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.DeleteCatalogItemRequest" + }, + { + "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_catalog_item" + }, + "description": "Sample for DeleteCatalogItem", + "file": "recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient.delete_catalog_item", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.DeleteCatalogItem", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "DeleteCatalogItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.DeleteCatalogItemRequest" + }, + { + "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_catalog_item" + }, + "description": "Sample for DeleteCatalogItem", + "file": "recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient.get_catalog_item", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.GetCatalogItem", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCatalogItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.GetCatalogItemRequest" + }, + { + "name": "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.recommendationengine_v1beta1.types.CatalogItem", + "shortName": "get_catalog_item" + }, + "description": "Sample for GetCatalogItem", + "file": "recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient.get_catalog_item", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.GetCatalogItem", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "GetCatalogItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.GetCatalogItemRequest" + }, + { + "name": "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.recommendationengine_v1beta1.types.CatalogItem", + "shortName": "get_catalog_item" + }, + "description": "Sample for GetCatalogItem", + "file": "recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient.import_catalog_items", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.ImportCatalogItems", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ImportCatalogItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "request_id", + "type": "str" + }, + { + "name": "input_config", + "type": "google.cloud.recommendationengine_v1beta1.types.InputConfig" + }, + { + "name": "errors_config", + "type": "google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig" + }, + { + "name": "retry", + "type": "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_catalog_items" + }, + "description": "Sample for ImportCatalogItems", + "file": "recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient.import_catalog_items", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.ImportCatalogItems", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ImportCatalogItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "request_id", + "type": "str" + }, + { + "name": "input_config", + "type": "google.cloud.recommendationengine_v1beta1.types.InputConfig" + }, + { + "name": "errors_config", + "type": "google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig" + }, + { + "name": "retry", + "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_catalog_items" + }, + "description": "Sample for ImportCatalogItems", + "file": "recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient.list_catalog_items", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.ListCatalogItems", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers.ListCatalogItemsAsyncPager", + "shortName": "list_catalog_items" + }, + "description": "Sample for ListCatalogItems", + "file": "recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient.list_catalog_items", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.ListCatalogItems", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "ListCatalogItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers.ListCatalogItemsPager", + "shortName": "list_catalog_items" + }, + "description": "Sample for ListCatalogItems", + "file": "recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient", + "shortName": "CatalogServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceAsyncClient.update_catalog_item", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.UpdateCatalogItem", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalogItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.UpdateCatalogItemRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "catalog_item", + "type": "google.cloud.recommendationengine_v1beta1.types.CatalogItem" + }, + { + "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.recommendationengine_v1beta1.types.CatalogItem", + "shortName": "update_catalog_item" + }, + "description": "Sample for UpdateCatalogItem", + "file": "recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient", + "shortName": "CatalogServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.CatalogServiceClient.update_catalog_item", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService.UpdateCatalogItem", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.CatalogService", + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalogItem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.UpdateCatalogItemRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "catalog_item", + "type": "google.cloud.recommendationengine_v1beta1.types.CatalogItem" + }, + { + "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.recommendationengine_v1beta1.types.CatalogItem", + "shortName": "update_catalog_item" + }, + "description": "Sample for UpdateCatalogItem", + "file": "recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient", + "shortName": "PredictionApiKeyRegistryAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient.create_prediction_api_key_registration", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry.CreatePredictionApiKeyRegistration", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry", + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "CreatePredictionApiKeyRegistration" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.CreatePredictionApiKeyRegistrationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "prediction_api_key_registration", + "type": "google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration", + "shortName": "create_prediction_api_key_registration" + }, + "description": "Sample for CreatePredictionApiKeyRegistration", + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryClient", + "shortName": "PredictionApiKeyRegistryClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryClient.create_prediction_api_key_registration", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry.CreatePredictionApiKeyRegistration", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry", + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "CreatePredictionApiKeyRegistration" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.CreatePredictionApiKeyRegistrationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "prediction_api_key_registration", + "type": "google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration", + "shortName": "create_prediction_api_key_registration" + }, + "description": "Sample for CreatePredictionApiKeyRegistration", + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient", + "shortName": "PredictionApiKeyRegistryAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient.delete_prediction_api_key_registration", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry.DeletePredictionApiKeyRegistration", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry", + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "DeletePredictionApiKeyRegistration" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.DeletePredictionApiKeyRegistrationRequest" + }, + { + "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_prediction_api_key_registration" + }, + "description": "Sample for DeletePredictionApiKeyRegistration", + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryClient", + "shortName": "PredictionApiKeyRegistryClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryClient.delete_prediction_api_key_registration", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry.DeletePredictionApiKeyRegistration", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry", + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "DeletePredictionApiKeyRegistration" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.DeletePredictionApiKeyRegistrationRequest" + }, + { + "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_prediction_api_key_registration" + }, + "description": "Sample for DeletePredictionApiKeyRegistration", + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient", + "shortName": "PredictionApiKeyRegistryAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient.list_prediction_api_key_registrations", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry.ListPredictionApiKeyRegistrations", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry", + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "ListPredictionApiKeyRegistrations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest" + }, + { + "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.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers.ListPredictionApiKeyRegistrationsAsyncPager", + "shortName": "list_prediction_api_key_registrations" + }, + "description": "Sample for ListPredictionApiKeyRegistrations", + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryClient", + "shortName": "PredictionApiKeyRegistryClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionApiKeyRegistryClient.list_prediction_api_key_registrations", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry.ListPredictionApiKeyRegistrations", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionApiKeyRegistry", + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "ListPredictionApiKeyRegistrations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest" + }, + { + "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.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers.ListPredictionApiKeyRegistrationsPager", + "shortName": "list_prediction_api_key_registrations" + }, + "description": "Sample for ListPredictionApiKeyRegistrations", + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionServiceAsyncClient", + "shortName": "PredictionServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionServiceAsyncClient.predict", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionService.Predict", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.PredictRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "user_event", + "type": "google.cloud.recommendationengine_v1beta1.types.UserEvent" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers.PredictAsyncPager", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "recommendationengine_v1beta1_generated_prediction_service_predict_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_PredictionService_Predict_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_prediction_service_predict_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionServiceClient", + "shortName": "PredictionServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.PredictionServiceClient.predict", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionService.Predict", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.PredictionService", + "shortName": "PredictionService" + }, + "shortName": "Predict" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.PredictRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "user_event", + "type": "google.cloud.recommendationengine_v1beta1.types.UserEvent" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers.PredictPager", + "shortName": "predict" + }, + "description": "Sample for Predict", + "file": "recommendationengine_v1beta1_generated_prediction_service_predict_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_PredictionService_Predict_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_prediction_service_predict_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.CollectUserEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_event", + "type": "str" + }, + { + "name": "uri", + "type": "str" + }, + { + "name": "ets", + "type": "int" + }, + { + "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": "recommendationengine_v1beta1_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.CollectUserEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_event", + "type": "str" + }, + { + "name": "uri", + "type": "str" + }, + { + "name": "ets", + "type": "int" + }, + { + "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": "recommendationengine_v1beta1_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.ImportUserEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "request_id", + "type": "str" + }, + { + "name": "input_config", + "type": "google.cloud.recommendationengine_v1beta1.types.InputConfig" + }, + { + "name": "errors_config", + "type": "google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig" + }, + { + "name": "retry", + "type": "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": "recommendationengine_v1beta1_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.ImportUserEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "request_id", + "type": "str" + }, + { + "name": "input_config", + "type": "google.cloud.recommendationengine_v1beta1.types.InputConfig" + }, + { + "name": "errors_config", + "type": "google.cloud.recommendationengine_v1beta1.types.ImportErrorsConfig" + }, + { + "name": "retry", + "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": "recommendationengine_v1beta1_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceAsyncClient.list_user_events", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService.ListUserEvents", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ListUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.ListUserEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers.ListUserEventsAsyncPager", + "shortName": "list_user_events" + }, + "description": "Sample for ListUserEvents", + "file": "recommendationengine_v1beta1_generated_user_event_service_list_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_user_event_service_list_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceClient.list_user_events", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService.ListUserEvents", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ListUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.ListUserEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers.ListUserEventsPager", + "shortName": "list_user_events" + }, + "description": "Sample for ListUserEvents", + "file": "recommendationengine_v1beta1_generated_user_event_service_list_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_user_event_service_list_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceAsyncClient.purge_user_events", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.PurgeUserEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "force", + "type": "bool" + }, + { + "name": "retry", + "type": "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": "recommendationengine_v1beta1_generated_user_event_service_purge_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_user_event_service_purge_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceClient.purge_user_events", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.PurgeUserEventsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "force", + "type": "bool" + }, + { + "name": "retry", + "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": "recommendationengine_v1beta1_generated_user_event_service_purge_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_user_event_service_purge_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.WriteUserEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_event", + "type": "google.cloud.recommendationengine_v1beta1.types.UserEvent" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "recommendationengine_v1beta1_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.recommendationengine_v1beta1.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.recommendationengine.v1beta1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.recommendationengine_v1beta1.types.WriteUserEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user_event", + "type": "google.cloud.recommendationengine_v1beta1.types.UserEvent" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.recommendationengine_v1beta1.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "recommendationengine_v1beta1_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "recommendationengine_v1beta1_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py new file mode 100644 index 00000000..721daf79 --- /dev/null +++ b/owl-bot-staging/v1beta1/scripts/fixup_recommendationengine_v1beta1_keywords.py @@ -0,0 +1,190 @@ +#! /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 recommendationengineCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'create_catalog_item': ('parent', 'catalog_item', ), + 'create_prediction_api_key_registration': ('parent', 'prediction_api_key_registration', ), + 'delete_catalog_item': ('name', ), + 'delete_prediction_api_key_registration': ('name', ), + 'get_catalog_item': ('name', ), + 'import_catalog_items': ('parent', 'input_config', 'request_id', 'errors_config', ), + 'import_user_events': ('parent', 'input_config', 'request_id', 'errors_config', ), + 'list_catalog_items': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_prediction_api_key_registrations': ('parent', 'page_size', 'page_token', ), + 'list_user_events': ('parent', 'page_size', 'page_token', 'filter', ), + 'predict': ('name', 'user_event', 'page_size', 'page_token', 'filter', 'dry_run', 'params', 'labels', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'update_catalog_item': ('name', 'catalog_item', '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=recommendationengineCallTransformer(), +): + """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 recommendationengine 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py new file mode 100644 index 00000000..fba40bae --- /dev/null +++ b/owl-bot-staging/v1beta1/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-recommendations-ai' + + +description = "Google Cloud Recommendations Ai API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/recommendationengine/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-recommendations-ai" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1beta1/testing/constraints-3.10.txt b/owl-bot-staging/v1beta1/testing/constraints-3.10.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta1/testing/constraints-3.11.txt b/owl-bot-staging/v1beta1/testing/constraints-3.11.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta1/testing/constraints-3.12.txt b/owl-bot-staging/v1beta1/testing/constraints-3.12.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta1/testing/constraints-3.7.txt b/owl-bot-staging/v1beta1/testing/constraints-3.7.txt new file mode 100644 index 00000000..6c44adfe --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/v1beta1/testing/constraints-3.8.txt b/owl-bot-staging/v1beta1/testing/constraints-3.8.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta1/testing/constraints-3.9.txt b/owl-bot-staging/v1beta1/testing/constraints-3.9.txt new file mode 100644 index 00000000..ed7f9aed --- /dev/null +++ b/owl-bot-staging/v1beta1/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/__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/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py new file mode 100644 index 00000000..dd58d300 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py @@ -0,0 +1,4526 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.recommendationengine_v1beta1.services.catalog_service import CatalogServiceAsyncClient +from google.cloud.recommendationengine_v1beta1.services.catalog_service import CatalogServiceClient +from google.cloud.recommendationengine_v1beta1.services.catalog_service import pagers +from google.cloud.recommendationengine_v1beta1.services.catalog_service import transports +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import catalog_service +from google.cloud.recommendationengine_v1beta1.types import common +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event +from google.longrunning import operations_pb2 +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"), + (CatalogServiceClient, "rest"), +]) +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 == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://recommendationengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CatalogServiceGrpcTransport, "grpc"), + (transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CatalogServiceRestTransport, "rest"), +]) +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"), + (CatalogServiceClient, "rest"), +]) +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 == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://recommendationengine.googleapis.com' + ) + + +def test_catalog_service_client_get_transport_class(): + transport = CatalogServiceClient.get_transport_class() + available_transports = [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceRestTransport, + ] + 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"), + (CatalogServiceClient, transports.CatalogServiceRestTransport, "rest"), +]) +@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"), + (CatalogServiceClient, transports.CatalogServiceRestTransport, "rest", "true"), + (CatalogServiceClient, transports.CatalogServiceRestTransport, "rest", "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"), + (CatalogServiceClient, transports.CatalogServiceRestTransport, "rest"), +]) +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), + (CatalogServiceClient, transports.CatalogServiceRestTransport, "rest", None), +]) +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.recommendationengine_v1beta1.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( + "recommendationengine.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="recommendationengine.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.CreateCatalogItemRequest, + dict, +]) +def test_create_catalog_item(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.create_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), + ) + response = client.create_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.CreateCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +def test_create_catalog_item_empty_call(): + # 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.create_catalog_item), + '__call__') as call: + client.create_catalog_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.CreateCatalogItemRequest() + +@pytest.mark.asyncio +async def test_create_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.CreateCatalogItemRequest): + 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.create_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + )) + response = await client.create_catalog_item(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.CreateCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +@pytest.mark.asyncio +async def test_create_catalog_item_async_from_dict(): + await test_create_catalog_item_async(request_type=dict) + + +def test_create_catalog_item_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.CreateCatalogItemRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_catalog_item), + '__call__') as call: + call.return_value = catalog.CatalogItem() + client.create_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_catalog_item_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.CreateCatalogItemRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_catalog_item), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + await client.create_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_catalog_item_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.create_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_catalog_item( + parent='parent_value', + catalog_item=catalog.CatalogItem(id='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].catalog_item + mock_val = catalog.CatalogItem(id='id_value') + assert arg == mock_val + + +def test_create_catalog_item_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.create_catalog_item( + catalog_service.CreateCatalogItemRequest(), + parent='parent_value', + catalog_item=catalog.CatalogItem(id='id_value'), + ) + +@pytest.mark.asyncio +async def test_create_catalog_item_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.create_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_catalog_item( + parent='parent_value', + catalog_item=catalog.CatalogItem(id='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].catalog_item + mock_val = catalog.CatalogItem(id='id_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_catalog_item_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.create_catalog_item( + catalog_service.CreateCatalogItemRequest(), + parent='parent_value', + catalog_item=catalog.CatalogItem(id='id_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetCatalogItemRequest, + dict, +]) +def test_get_catalog_item(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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), + ) + response = client.get_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +def test_get_catalog_item_empty_call(): + # 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_catalog_item), + '__call__') as call: + client.get_catalog_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.GetCatalogItemRequest() + +@pytest.mark.asyncio +async def test_get_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.GetCatalogItemRequest): + 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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + )) + response = await client.get_catalog_item(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.GetCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +@pytest.mark.asyncio +async def test_get_catalog_item_async_from_dict(): + await test_get_catalog_item_async(request_type=dict) + + +def test_get_catalog_item_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.GetCatalogItemRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_catalog_item), + '__call__') as call: + call.return_value = catalog.CatalogItem() + client.get_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_catalog_item_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.GetCatalogItemRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_catalog_item), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + await client.get_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_catalog_item_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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_catalog_item( + 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_catalog_item_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_catalog_item( + catalog_service.GetCatalogItemRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_catalog_item_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_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_catalog_item( + 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_catalog_item_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_catalog_item( + catalog_service.GetCatalogItemRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ListCatalogItemsRequest, + dict, +]) +def test_list_catalog_items(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_catalog_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogItemsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_catalog_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogItemsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogItemsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalog_items_empty_call(): + # 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_catalog_items), + '__call__') as call: + client.list_catalog_items() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.ListCatalogItemsRequest() + +@pytest.mark.asyncio +async def test_list_catalog_items_async(transport: str = 'grpc_asyncio', request_type=catalog_service.ListCatalogItemsRequest): + 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_catalog_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogItemsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_catalog_items(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.ListCatalogItemsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogItemsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_catalog_items_async_from_dict(): + await test_list_catalog_items_async(request_type=dict) + + +def test_list_catalog_items_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.ListCatalogItemsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), + '__call__') as call: + call.return_value = catalog_service.ListCatalogItemsResponse() + client.list_catalog_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_catalog_items_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.ListCatalogItemsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_catalog_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogItemsResponse()) + await client.list_catalog_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_catalog_items_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_catalog_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogItemsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_catalog_items( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + + +def test_list_catalog_items_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_catalog_items( + catalog_service.ListCatalogItemsRequest(), + parent='parent_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_list_catalog_items_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_catalog_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog_service.ListCatalogItemsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog_service.ListCatalogItemsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_catalog_items( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_catalog_items_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_catalog_items( + catalog_service.ListCatalogItemsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_catalog_items_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_catalog_items), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[], + next_page_token='def', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_catalog_items(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, catalog.CatalogItem) + for i in results) +def test_list_catalog_items_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_catalog_items), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[], + next_page_token='def', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + ), + RuntimeError, + ) + pages = list(client.list_catalog_items(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_catalog_items_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_catalog_items), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[], + next_page_token='def', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_catalog_items(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.CatalogItem) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_catalog_items_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_catalog_items), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[], + next_page_token='def', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_catalog_items(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.UpdateCatalogItemRequest, + dict, +]) +def test_update_catalog_item(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_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), + ) + response = client.update_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +def test_update_catalog_item_empty_call(): + # 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_item), + '__call__') as call: + client.update_catalog_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.UpdateCatalogItemRequest() + +@pytest.mark.asyncio +async def test_update_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.UpdateCatalogItemRequest): + 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_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + )) + response = await client.update_catalog_item(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.UpdateCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +@pytest.mark.asyncio +async def test_update_catalog_item_async_from_dict(): + await test_update_catalog_item_async(request_type=dict) + + +def test_update_catalog_item_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.UpdateCatalogItemRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog_item), + '__call__') as call: + call.return_value = catalog.CatalogItem() + client.update_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_catalog_item_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.UpdateCatalogItemRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_catalog_item), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + await client.update_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_update_catalog_item_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_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_catalog_item( + name='name_value', + catalog_item=catalog.CatalogItem(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].catalog_item + mock_val = catalog.CatalogItem(id='id_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_item_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_item( + catalog_service.UpdateCatalogItemRequest(), + name='name_value', + catalog_item=catalog.CatalogItem(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_catalog_item_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_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = catalog.CatalogItem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(catalog.CatalogItem()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_catalog_item( + name='name_value', + catalog_item=catalog.CatalogItem(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].catalog_item + mock_val = catalog.CatalogItem(id='id_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_item_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_item( + catalog_service.UpdateCatalogItemRequest(), + name='name_value', + catalog_item=catalog.CatalogItem(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.DeleteCatalogItemRequest, + dict, +]) +def test_delete_catalog_item(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.delete_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.DeleteCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_catalog_item_empty_call(): + # 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.delete_catalog_item), + '__call__') as call: + client.delete_catalog_item() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == catalog_service.DeleteCatalogItemRequest() + +@pytest.mark.asyncio +async def test_delete_catalog_item_async(transport: str = 'grpc_asyncio', request_type=catalog_service.DeleteCatalogItemRequest): + 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.delete_catalog_item), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_catalog_item(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.DeleteCatalogItemRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_catalog_item_async_from_dict(): + await test_delete_catalog_item_async(request_type=dict) + + +def test_delete_catalog_item_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.DeleteCatalogItemRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_catalog_item), + '__call__') as call: + call.return_value = None + client.delete_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_catalog_item_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.DeleteCatalogItemRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_catalog_item), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_catalog_item(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_catalog_item_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.delete_catalog_item), + '__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_catalog_item( + 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_catalog_item_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.delete_catalog_item( + catalog_service.DeleteCatalogItemRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_catalog_item_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.delete_catalog_item), + '__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_catalog_item( + 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_catalog_item_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.delete_catalog_item( + catalog_service.DeleteCatalogItemRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + import_.ImportCatalogItemsRequest, + dict, +]) +def test_import_catalog_items(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.import_catalog_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_catalog_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_.ImportCatalogItemsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_catalog_items_empty_call(): + # 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.import_catalog_items), + '__call__') as call: + client.import_catalog_items() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_.ImportCatalogItemsRequest() + +@pytest.mark.asyncio +async def test_import_catalog_items_async(transport: str = 'grpc_asyncio', request_type=import_.ImportCatalogItemsRequest): + 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.import_catalog_items), + '__call__') as call: + # 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_catalog_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_.ImportCatalogItemsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_catalog_items_async_from_dict(): + await test_import_catalog_items_async(request_type=dict) + + +def test_import_catalog_items_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 = import_.ImportCatalogItemsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_catalog_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_catalog_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_catalog_items_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 = import_.ImportCatalogItemsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_catalog_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_catalog_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_import_catalog_items_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.import_catalog_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.import_catalog_items( + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + # Establish that the 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].request_id + mock_val = 'request_id_value' + assert arg == mock_val + arg = args[0].input_config + mock_val = import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) + assert arg == mock_val + arg = args[0].errors_config + mock_val = import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') + assert arg == mock_val + + +def test_import_catalog_items_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.import_catalog_items( + import_.ImportCatalogItemsRequest(), + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + +@pytest.mark.asyncio +async def test_import_catalog_items_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.import_catalog_items), + '__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.import_catalog_items( + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + # Establish that 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].request_id + mock_val = 'request_id_value' + assert arg == mock_val + arg = args[0].input_config + mock_val = import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) + assert arg == mock_val + arg = args[0].errors_config + mock_val = import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_import_catalog_items_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.import_catalog_items( + import_.ImportCatalogItemsRequest(), + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.CreateCatalogItemRequest, + dict, +]) +def test_create_catalog_item_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3'} + request_init["catalog_item"] = {'id': 'id_value', 'category_hierarchies': [{'categories': ['categories_value1', 'categories_value2']}], 'title': 'title_value', 'description': 'description_value', 'item_attributes': {'categorical_features': {}, 'numerical_features': {}}, 'language_code': 'language_code_value', 'tags': ['tags_value1', 'tags_value2'], 'item_group_id': 'item_group_id_value', 'product_metadata': {'exact_price': {'display_price': 0.1384, 'original_price': 0.1479}, 'price_range': {'min_': 0.419, 'max_': 0.421}, 'costs': {}, 'currency_code': 'currency_code_value', 'stock_state': 1, 'available_quantity': 1919, 'canonical_product_uri': 'canonical_product_uri_value', 'images': [{'uri': 'uri_value', 'height': 633, 'width': 544}]}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_catalog_item(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +def test_create_catalog_item_rest_required_fields(request_type=catalog_service.CreateCatalogItemRequest): + transport_class = transports.CatalogServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_catalog_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_catalog_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = catalog.CatalogItem() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_catalog_item(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_catalog_item_rest_unset_required_fields(): + transport = transports.CatalogServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_catalog_item._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "catalogItem", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_catalog_item_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.CatalogServiceRestInterceptor, "post_create_catalog_item") as post, \ + mock.patch.object(transports.CatalogServiceRestInterceptor, "pre_create_catalog_item") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.CreateCatalogItemRequest.pb(catalog_service.CreateCatalogItemRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = catalog.CatalogItem.to_json(catalog.CatalogItem()) + + request = catalog_service.CreateCatalogItemRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CatalogItem() + + client.create_catalog_item(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_catalog_item_rest_bad_request(transport: str = 'rest', request_type=catalog_service.CreateCatalogItemRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3'} + request_init["catalog_item"] = {'id': 'id_value', 'category_hierarchies': [{'categories': ['categories_value1', 'categories_value2']}], 'title': 'title_value', 'description': 'description_value', 'item_attributes': {'categorical_features': {}, 'numerical_features': {}}, 'language_code': 'language_code_value', 'tags': ['tags_value1', 'tags_value2'], 'item_group_id': 'item_group_id_value', 'product_metadata': {'exact_price': {'display_price': 0.1384, 'original_price': 0.1479}, 'price_range': {'min_': 0.419, 'max_': 0.421}, 'costs': {}, 'currency_code': 'currency_code_value', 'stock_state': 1, 'available_quantity': 1919, 'canonical_product_uri': 'canonical_product_uri_value', 'images': [{'uri': 'uri_value', 'height': 633, 'width': 544}]}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_catalog_item(request) + + +def test_create_catalog_item_rest_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = catalog.CatalogItem() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + catalog_item=catalog.CatalogItem(id='id_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_catalog_item(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems" % client.transport._host, args[1]) + + +def test_create_catalog_item_rest_flattened_error(transport: str = 'rest'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_catalog_item( + catalog_service.CreateCatalogItemRequest(), + parent='parent_value', + catalog_item=catalog.CatalogItem(id='id_value'), + ) + + +def test_create_catalog_item_rest_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.GetCatalogItemRequest, + dict, +]) +def test_get_catalog_item_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_catalog_item(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +def test_get_catalog_item_rest_required_fields(request_type=catalog_service.GetCatalogItemRequest): + transport_class = transports.CatalogServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_catalog_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_catalog_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = catalog.CatalogItem() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_catalog_item(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_catalog_item_rest_unset_required_fields(): + transport = transports.CatalogServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_catalog_item._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_catalog_item_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.CatalogServiceRestInterceptor, "post_get_catalog_item") as post, \ + mock.patch.object(transports.CatalogServiceRestInterceptor, "pre_get_catalog_item") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.GetCatalogItemRequest.pb(catalog_service.GetCatalogItemRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = catalog.CatalogItem.to_json(catalog.CatalogItem()) + + request = catalog_service.GetCatalogItemRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CatalogItem() + + client.get_catalog_item(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_catalog_item_rest_bad_request(transport: str = 'rest', request_type=catalog_service.GetCatalogItemRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_catalog_item(request) + + +def test_get_catalog_item_rest_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = catalog.CatalogItem() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_catalog_item(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}" % client.transport._host, args[1]) + + +def test_get_catalog_item_rest_flattened_error(transport: str = 'rest'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_catalog_item( + catalog_service.GetCatalogItemRequest(), + name='name_value', + ) + + +def test_get_catalog_item_rest_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.ListCatalogItemsRequest, + dict, +]) +def test_list_catalog_items_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = catalog_service.ListCatalogItemsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = catalog_service.ListCatalogItemsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_catalog_items(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCatalogItemsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_catalog_items_rest_required_fields(request_type=catalog_service.ListCatalogItemsRequest): + transport_class = transports.CatalogServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_catalog_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_catalog_items._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = catalog_service.ListCatalogItemsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = catalog_service.ListCatalogItemsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_catalog_items(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_catalog_items_rest_unset_required_fields(): + transport = transports.CatalogServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_catalog_items._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_catalog_items_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.CatalogServiceRestInterceptor, "post_list_catalog_items") as post, \ + mock.patch.object(transports.CatalogServiceRestInterceptor, "pre_list_catalog_items") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.ListCatalogItemsRequest.pb(catalog_service.ListCatalogItemsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = catalog_service.ListCatalogItemsResponse.to_json(catalog_service.ListCatalogItemsResponse()) + + request = catalog_service.ListCatalogItemsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog_service.ListCatalogItemsResponse() + + client.list_catalog_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_catalog_items_rest_bad_request(transport: str = 'rest', request_type=catalog_service.ListCatalogItemsRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_catalog_items(request) + + +def test_list_catalog_items_rest_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = catalog_service.ListCatalogItemsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + filter='filter_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = catalog_service.ListCatalogItemsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_catalog_items(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems" % client.transport._host, args[1]) + + +def test_list_catalog_items_rest_flattened_error(transport: str = 'rest'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_catalog_items( + catalog_service.ListCatalogItemsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_catalog_items_rest_pager(transport: str = 'rest'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + next_page_token='abc', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[], + next_page_token='def', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + ], + next_page_token='ghi', + ), + catalog_service.ListCatalogItemsResponse( + catalog_items=[ + catalog.CatalogItem(), + catalog.CatalogItem(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(catalog_service.ListCatalogItemsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3'} + + pager = client.list_catalog_items(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, catalog.CatalogItem) + for i in results) + + pages = list(client.list_catalog_items(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + catalog_service.UpdateCatalogItemRequest, + dict, +]) +def test_update_catalog_item_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4'} + request_init["catalog_item"] = {'id': 'id_value', 'category_hierarchies': [{'categories': ['categories_value1', 'categories_value2']}], 'title': 'title_value', 'description': 'description_value', 'item_attributes': {'categorical_features': {}, 'numerical_features': {}}, 'language_code': 'language_code_value', 'tags': ['tags_value1', 'tags_value2'], 'item_group_id': 'item_group_id_value', 'product_metadata': {'exact_price': {'display_price': 0.1384, 'original_price': 0.1479}, 'price_range': {'min_': 0.419, 'max_': 0.421}, 'costs': {}, 'currency_code': 'currency_code_value', 'stock_state': 1, 'available_quantity': 1919, 'canonical_product_uri': 'canonical_product_uri_value', 'images': [{'uri': 'uri_value', 'height': 633, 'width': 544}]}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = catalog.CatalogItem( + id='id_value', + title='title_value', + description='description_value', + language_code='language_code_value', + tags=['tags_value'], + item_group_id='item_group_id_value', + product_metadata=catalog.ProductCatalogItem(exact_price=catalog.ProductCatalogItem.ExactPrice(display_price=0.1384)), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_catalog_item(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, catalog.CatalogItem) + assert response.id == 'id_value' + assert response.title == 'title_value' + assert response.description == 'description_value' + assert response.language_code == 'language_code_value' + assert response.tags == ['tags_value'] + assert response.item_group_id == 'item_group_id_value' + + +def test_update_catalog_item_rest_required_fields(request_type=catalog_service.UpdateCatalogItemRequest): + transport_class = transports.CatalogServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_catalog_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_catalog_item._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = catalog.CatalogItem() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_catalog_item(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_catalog_item_rest_unset_required_fields(): + transport = transports.CatalogServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_catalog_item._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("name", "catalogItem", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_catalog_item_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.CatalogServiceRestInterceptor, "post_update_catalog_item") as post, \ + mock.patch.object(transports.CatalogServiceRestInterceptor, "pre_update_catalog_item") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = catalog_service.UpdateCatalogItemRequest.pb(catalog_service.UpdateCatalogItemRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = catalog.CatalogItem.to_json(catalog.CatalogItem()) + + request = catalog_service.UpdateCatalogItemRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = catalog.CatalogItem() + + client.update_catalog_item(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_catalog_item_rest_bad_request(transport: str = 'rest', request_type=catalog_service.UpdateCatalogItemRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4'} + request_init["catalog_item"] = {'id': 'id_value', 'category_hierarchies': [{'categories': ['categories_value1', 'categories_value2']}], 'title': 'title_value', 'description': 'description_value', 'item_attributes': {'categorical_features': {}, 'numerical_features': {}}, 'language_code': 'language_code_value', 'tags': ['tags_value1', 'tags_value2'], 'item_group_id': 'item_group_id_value', 'product_metadata': {'exact_price': {'display_price': 0.1384, 'original_price': 0.1479}, 'price_range': {'min_': 0.419, 'max_': 0.421}, 'costs': {}, 'currency_code': 'currency_code_value', 'stock_state': 1, 'available_quantity': 1919, 'canonical_product_uri': 'canonical_product_uri_value', 'images': [{'uri': 'uri_value', 'height': 633, 'width': 544}]}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_catalog_item(request) + + +def test_update_catalog_item_rest_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = catalog.CatalogItem() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + catalog_item=catalog.CatalogItem(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = catalog.CatalogItem.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_catalog_item(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}" % client.transport._host, args[1]) + + +def test_update_catalog_item_rest_flattened_error(transport: str = 'rest'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_catalog_item( + catalog_service.UpdateCatalogItemRequest(), + name='name_value', + catalog_item=catalog.CatalogItem(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_catalog_item_rest_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + catalog_service.DeleteCatalogItemRequest, + dict, +]) +def test_delete_catalog_item_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_catalog_item(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_catalog_item_rest_required_fields(request_type=catalog_service.DeleteCatalogItemRequest): + transport_class = transports.CatalogServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_catalog_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_catalog_item._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_catalog_item(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_catalog_item_rest_unset_required_fields(): + transport = transports.CatalogServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_catalog_item._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_catalog_item_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.CatalogServiceRestInterceptor, "pre_delete_catalog_item") as pre: + pre.assert_not_called() + pb_message = catalog_service.DeleteCatalogItemRequest.pb(catalog_service.DeleteCatalogItemRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = catalog_service.DeleteCatalogItemRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_catalog_item(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_catalog_item_rest_bad_request(transport: str = 'rest', request_type=catalog_service.DeleteCatalogItemRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_catalog_item(request) + + +def test_delete_catalog_item_rest_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/catalogItems/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_catalog_item(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/catalogs/*/catalogItems/**}" % client.transport._host, args[1]) + + +def test_delete_catalog_item_rest_flattened_error(transport: str = 'rest'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_catalog_item( + catalog_service.DeleteCatalogItemRequest(), + name='name_value', + ) + + +def test_delete_catalog_item_rest_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + import_.ImportCatalogItemsRequest, + dict, +]) +def test_import_catalog_items_rest(request_type): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.import_catalog_items(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_import_catalog_items_rest_required_fields(request_type=import_.ImportCatalogItemsRequest): + transport_class = transports.CatalogServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_catalog_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_catalog_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.import_catalog_items(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_catalog_items_rest_unset_required_fields(): + transport = transports.CatalogServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_catalog_items._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "inputConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_catalog_items_rest_interceptors(null_interceptor): + transport = transports.CatalogServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CatalogServiceRestInterceptor(), + ) + client = CatalogServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.CatalogServiceRestInterceptor, "post_import_catalog_items") as post, \ + mock.patch.object(transports.CatalogServiceRestInterceptor, "pre_import_catalog_items") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_.ImportCatalogItemsRequest.pb(import_.ImportCatalogItemsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = import_.ImportCatalogItemsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_catalog_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_catalog_items_rest_bad_request(transport: str = 'rest', request_type=import_.ImportCatalogItemsRequest): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.import_catalog_items(request) + + +def test_import_catalog_items_rest_flattened(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.import_catalog_items(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/catalogs/*}/catalogItems:import" % client.transport._host, args[1]) + + +def test_import_catalog_items_rest_flattened_error(transport: str = 'rest'): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_catalog_items( + import_.ImportCatalogItemsRequest(), + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + +def test_import_catalog_items_rest_error(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +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, + transports.CatalogServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = 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.recommendationengine_v1beta1.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 = ( + 'create_catalog_item', + 'get_catalog_item', + 'list_catalog_items', + 'update_catalog_item', + 'delete_catalog_item', + 'import_catalog_items', + ) + 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_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.recommendationengine_v1beta1.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.recommendationengine_v1beta1.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( + "recommendationengine.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="recommendationengine.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 + ) + +def test_catalog_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.CatalogServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_catalog_service_rest_lro_client(): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_catalog_service_host_no_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://recommendationengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_catalog_service_host_with_port(transport_name): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'recommendationengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://recommendationengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_catalog_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CatalogServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CatalogServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_catalog_item._session + session2 = client2.transport.create_catalog_item._session + assert session1 != session2 + session1 = client1.transport.get_catalog_item._session + session2 = client2.transport.get_catalog_item._session + assert session1 != session2 + session1 = client1.transport.list_catalog_items._session + session2 = client2.transport.list_catalog_items._session + assert session1 != session2 + session1 = client1.transport.update_catalog_item._session + session2 = client2.transport.update_catalog_item._session + assert session1 != session2 + session1 = client1.transport.delete_catalog_item._session + session2 = client2.transport.delete_catalog_item._session + assert session1 != session2 + session1 = client1.transport.import_catalog_items._session + session2 = client2.transport.import_catalog_items._session + assert session1 != session2 +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_catalog_service_grpc_lro_client(): + client = CatalogServiceClient( + 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_catalog_service_grpc_lro_async_client(): + client = CatalogServiceAsyncClient( + 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 = CatalogServiceClient.catalog_path(project, location, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "octopus", + "location": "oyster", + "catalog": "nudibranch", + } + path = CatalogServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_path(path) + assert expected == actual + +def test_catalog_item_path_path(): + project = "cuttlefish" + location = "mussel" + catalog = "winkle" + catalog_item_path = "nautilus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/catalogItems/{catalog_item_path}".format(project=project, location=location, catalog=catalog, catalog_item_path=catalog_item_path, ) + actual = CatalogServiceClient.catalog_item_path_path(project, location, catalog, catalog_item_path) + assert expected == actual + + +def test_parse_catalog_item_path_path(): + expected = { + "project": "scallop", + "location": "abalone", + "catalog": "squid", + "catalog_item_path": "clam", + } + path = CatalogServiceClient.catalog_item_path_path(**expected) + + # Check that the path construction is reversible. + actual = CatalogServiceClient.parse_catalog_item_path_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 = { + "rest": "_session", + "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 = [ + 'rest', + '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/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py new file mode 100644 index 00000000..ca68a389 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py @@ -0,0 +1,2888 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import PredictionApiKeyRegistryAsyncClient +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import PredictionApiKeyRegistryClient +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import pagers +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import transports +from google.cloud.recommendationengine_v1beta1.types import prediction_apikey_registry_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 PredictionApiKeyRegistryClient._get_default_mtls_endpoint(None) is None + assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert PredictionApiKeyRegistryClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (PredictionApiKeyRegistryClient, "grpc"), + (PredictionApiKeyRegistryAsyncClient, "grpc_asyncio"), + (PredictionApiKeyRegistryClient, "rest"), +]) +def test_prediction_api_key_registry_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 == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://recommendationengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), + (transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.PredictionApiKeyRegistryRestTransport, "rest"), +]) +def test_prediction_api_key_registry_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", [ + (PredictionApiKeyRegistryClient, "grpc"), + (PredictionApiKeyRegistryAsyncClient, "grpc_asyncio"), + (PredictionApiKeyRegistryClient, "rest"), +]) +def test_prediction_api_key_registry_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 == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://recommendationengine.googleapis.com' + ) + + +def test_prediction_api_key_registry_client_get_transport_class(): + transport = PredictionApiKeyRegistryClient.get_transport_class() + available_transports = [ + transports.PredictionApiKeyRegistryGrpcTransport, + transports.PredictionApiKeyRegistryRestTransport, + ] + assert transport in available_transports + + transport = PredictionApiKeyRegistryClient.get_transport_class("grpc") + assert transport == transports.PredictionApiKeyRegistryGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryRestTransport, "rest"), +]) +@mock.patch.object(PredictionApiKeyRegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryClient)) +@mock.patch.object(PredictionApiKeyRegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryAsyncClient)) +def test_prediction_api_key_registry_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(PredictionApiKeyRegistryClient, '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(PredictionApiKeyRegistryClient, '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", [ + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc", "true"), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc", "false"), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryRestTransport, "rest", "true"), + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryRestTransport, "rest", "false"), +]) +@mock.patch.object(PredictionApiKeyRegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryClient)) +@mock.patch.object(PredictionApiKeyRegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_prediction_api_key_registry_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", [ + PredictionApiKeyRegistryClient, PredictionApiKeyRegistryAsyncClient +]) +@mock.patch.object(PredictionApiKeyRegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryClient)) +@mock.patch.object(PredictionApiKeyRegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PredictionApiKeyRegistryAsyncClient)) +def test_prediction_api_key_registry_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", [ + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc"), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio"), + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryRestTransport, "rest"), +]) +def test_prediction_api_key_registry_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", [ + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc", grpc_helpers), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryRestTransport, "rest", None), +]) +def test_prediction_api_key_registry_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_api_key_registry_client_client_options_from_dict(): + with mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = PredictionApiKeyRegistryClient( + 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", [ + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc", grpc_helpers), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_prediction_api_key_registry_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( + "recommendationengine.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="recommendationengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, + dict, +]) +def test_create_prediction_api_key_registration(request_type, transport: str = 'grpc'): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration( + api_key='api_key_value', + ) + response = client.create_prediction_api_key_registration(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_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_apikey_registry_service.PredictionApiKeyRegistration) + assert response.api_key == 'api_key_value' + + +def test_create_prediction_api_key_registration_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registration), + '__call__') as call: + client.create_prediction_api_key_registration() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + +@pytest.mark.asyncio +async def test_create_prediction_api_key_registration_async(transport: str = 'grpc_asyncio', request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.PredictionApiKeyRegistration( + api_key='api_key_value', + )) + response = await client.create_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_apikey_registry_service.PredictionApiKeyRegistration) + assert response.api_key == 'api_key_value' + + +@pytest.mark.asyncio +async def test_create_prediction_api_key_registration_async_from_dict(): + await test_create_prediction_api_key_registration_async(request_type=dict) + + +def test_create_prediction_api_key_registration_field_headers(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_prediction_api_key_registration), + '__call__') as call: + call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() + client.create_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_prediction_api_key_registration_field_headers_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_prediction_api_key_registration), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.PredictionApiKeyRegistration()) + await client.create_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_prediction_api_key_registration_flattened(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_prediction_api_key_registration( + parent='parent_value', + prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), + ) + + # Establish that the 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].prediction_api_key_registration + mock_val = prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value') + assert arg == mock_val + + +def test_create_prediction_api_key_registration_flattened_error(): + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registration( + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(), + parent='parent_value', + prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), + ) + +@pytest.mark.asyncio +async def test_create_prediction_api_key_registration_flattened_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.PredictionApiKeyRegistration()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_prediction_api_key_registration( + parent='parent_value', + prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), + ) + + # Establish that 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].prediction_api_key_registration + mock_val = prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_prediction_api_key_registration_flattened_error_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_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_prediction_api_key_registration( + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(), + parent='parent_value', + prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, + dict, +]) +def test_list_prediction_api_key_registrations(request_type, transport: str = 'grpc'): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registrations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_prediction_api_key_registrations(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_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPredictionApiKeyRegistrationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_prediction_api_key_registrations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registrations), + '__call__') as call: + client.list_prediction_api_key_registrations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + +@pytest.mark.asyncio +async def test_list_prediction_api_key_registrations_async(transport: str = 'grpc_asyncio', request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registrations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_prediction_api_key_registrations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPredictionApiKeyRegistrationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_prediction_api_key_registrations_async_from_dict(): + await test_list_prediction_api_key_registrations_async(request_type=dict) + + +def test_list_prediction_api_key_registrations_field_headers(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__') as call: + call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + client.list_prediction_api_key_registrations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_prediction_api_key_registrations_field_headers_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse()) + await client.list_prediction_api_key_registrations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_prediction_api_key_registrations_flattened(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_prediction_api_key_registrations( + 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_prediction_api_key_registrations_flattened_error(): + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registrations( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_prediction_api_key_registrations_flattened_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_prediction_api_key_registrations( + 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_prediction_api_key_registrations_flattened_error_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_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_prediction_api_key_registrations( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(), + parent='parent_value', + ) + + +def test_list_prediction_api_key_registrations_pager(transport_name: str = "grpc"): + client = PredictionApiKeyRegistryClient( + credentials=ga_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_prediction_api_key_registrations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='abc', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[], + next_page_token='def', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='ghi', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_prediction_api_key_registrations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, prediction_apikey_registry_service.PredictionApiKeyRegistration) + for i in results) +def test_list_prediction_api_key_registrations_pages(transport_name: str = "grpc"): + client = PredictionApiKeyRegistryClient( + credentials=ga_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_prediction_api_key_registrations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='abc', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[], + next_page_token='def', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='ghi', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + ), + RuntimeError, + ) + pages = list(client.list_prediction_api_key_registrations(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_prediction_api_key_registrations_async_pager(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='abc', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[], + next_page_token='def', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='ghi', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_prediction_api_key_registrations(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, prediction_apikey_registry_service.PredictionApiKeyRegistration) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_prediction_api_key_registrations_async_pages(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_prediction_api_key_registrations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='abc', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[], + next_page_token='def', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='ghi', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_prediction_api_key_registrations(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", [ + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, + dict, +]) +def test_delete_prediction_api_key_registration(request_type, transport: str = 'grpc'): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_prediction_api_key_registration(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_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_prediction_api_key_registration_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registration), + '__call__') as call: + client.delete_prediction_api_key_registration() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + +@pytest.mark.asyncio +async def test_delete_prediction_api_key_registration_async(transport: str = 'grpc_asyncio', request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_prediction_api_key_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_prediction_api_key_registration_async_from_dict(): + await test_delete_prediction_api_key_registration_async(request_type=dict) + + +def test_delete_prediction_api_key_registration_field_headers(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_prediction_api_key_registration), + '__call__') as call: + call.return_value = None + client.delete_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_prediction_api_key_registration_field_headers_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_prediction_api_key_registration), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_prediction_api_key_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_prediction_api_key_registration_flattened(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_prediction_api_key_registration), + '__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_prediction_api_key_registration( + 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_prediction_api_key_registration_flattened_error(): + client = PredictionApiKeyRegistryClient( + credentials=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_prediction_api_key_registration( + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_prediction_api_key_registration_flattened_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_prediction_api_key_registration), + '__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_prediction_api_key_registration( + 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_prediction_api_key_registration_flattened_error_async(): + client = PredictionApiKeyRegistryAsyncClient( + credentials=ga_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_prediction_api_key_registration( + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, + dict, +]) +def test_create_prediction_api_key_registration_rest(request_type): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration( + api_key='api_key_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_prediction_api_key_registration(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, prediction_apikey_registry_service.PredictionApiKeyRegistration) + assert response.api_key == 'api_key_value' + + +def test_create_prediction_api_key_registration_rest_required_fields(request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest): + transport_class = transports.PredictionApiKeyRegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_prediction_api_key_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_prediction_api_key_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_prediction_api_key_registration(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_prediction_api_key_registration_rest_unset_required_fields(): + transport = transports.PredictionApiKeyRegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_prediction_api_key_registration._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "predictionApiKeyRegistration", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_prediction_api_key_registration_rest_interceptors(null_interceptor): + transport = transports.PredictionApiKeyRegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PredictionApiKeyRegistryRestInterceptor(), + ) + client = PredictionApiKeyRegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PredictionApiKeyRegistryRestInterceptor, "post_create_prediction_api_key_registration") as post, \ + mock.patch.object(transports.PredictionApiKeyRegistryRestInterceptor, "pre_create_prediction_api_key_registration") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest.pb(prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = prediction_apikey_registry_service.PredictionApiKeyRegistration.to_json(prediction_apikey_registry_service.PredictionApiKeyRegistration()) + + request = prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() + + client.create_prediction_api_key_registration(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_prediction_api_key_registration_rest_bad_request(transport: str = 'rest', request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_prediction_api_key_registration(request) + + +def test_create_prediction_api_key_registration_rest_flattened(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = prediction_apikey_registry_service.PredictionApiKeyRegistration.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_prediction_api_key_registration(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/predictionApiKeyRegistrations" % client.transport._host, args[1]) + + +def test_create_prediction_api_key_registration_rest_flattened_error(transport: str = 'rest'): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_prediction_api_key_registration( + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest(), + parent='parent_value', + prediction_api_key_registration=prediction_apikey_registry_service.PredictionApiKeyRegistration(api_key='api_key_value'), + ) + + +def test_create_prediction_api_key_registration_rest_error(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, + dict, +]) +def test_list_prediction_api_key_registrations_rest(request_type): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_prediction_api_key_registrations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPredictionApiKeyRegistrationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_prediction_api_key_registrations_rest_required_fields(request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest): + transport_class = transports.PredictionApiKeyRegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_prediction_api_key_registrations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_prediction_api_key_registrations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_prediction_api_key_registrations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_prediction_api_key_registrations_rest_unset_required_fields(): + transport = transports.PredictionApiKeyRegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_prediction_api_key_registrations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_prediction_api_key_registrations_rest_interceptors(null_interceptor): + transport = transports.PredictionApiKeyRegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PredictionApiKeyRegistryRestInterceptor(), + ) + client = PredictionApiKeyRegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PredictionApiKeyRegistryRestInterceptor, "post_list_prediction_api_key_registrations") as post, \ + mock.patch.object(transports.PredictionApiKeyRegistryRestInterceptor, "pre_list_prediction_api_key_registrations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest.pb(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.to_json(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse()) + + request = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + + client.list_prediction_api_key_registrations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_prediction_api_key_registrations_rest_bad_request(transport: str = 'rest', request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_prediction_api_key_registrations(request) + + +def test_list_prediction_api_key_registrations_rest_flattened(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_prediction_api_key_registrations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/predictionApiKeyRegistrations" % client.transport._host, args[1]) + + +def test_list_prediction_api_key_registrations_rest_flattened_error(transport: str = 'rest'): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_prediction_api_key_registrations( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest(), + parent='parent_value', + ) + + +def test_list_prediction_api_key_registrations_rest_pager(transport: str = 'rest'): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='abc', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[], + next_page_token='def', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + next_page_token='ghi', + ), + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse( + prediction_api_key_registrations=[ + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + prediction_apikey_registry_service.PredictionApiKeyRegistration(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + + pager = client.list_prediction_api_key_registrations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, prediction_apikey_registry_service.PredictionApiKeyRegistration) + for i in results) + + pages = list(client.list_prediction_api_key_registrations(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, + dict, +]) +def test_delete_prediction_api_key_registration_rest(request_type): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/predictionApiKeyRegistrations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_prediction_api_key_registration(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_prediction_api_key_registration_rest_required_fields(request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest): + transport_class = transports.PredictionApiKeyRegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_prediction_api_key_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_prediction_api_key_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_prediction_api_key_registration(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_prediction_api_key_registration_rest_unset_required_fields(): + transport = transports.PredictionApiKeyRegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_prediction_api_key_registration._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_prediction_api_key_registration_rest_interceptors(null_interceptor): + transport = transports.PredictionApiKeyRegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PredictionApiKeyRegistryRestInterceptor(), + ) + client = PredictionApiKeyRegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PredictionApiKeyRegistryRestInterceptor, "pre_delete_prediction_api_key_registration") as pre: + pre.assert_not_called() + pb_message = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest.pb(prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_prediction_api_key_registration(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_prediction_api_key_registration_rest_bad_request(transport: str = 'rest', request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/predictionApiKeyRegistrations/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_prediction_api_key_registration(request) + + +def test_delete_prediction_api_key_registration_rest_flattened(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/predictionApiKeyRegistrations/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_prediction_api_key_registration(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/predictionApiKeyRegistrations/*}" % client.transport._host, args[1]) + + +def test_delete_prediction_api_key_registration_rest_flattened_error(transport: str = 'rest'): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_prediction_api_key_registration( + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest(), + name='name_value', + ) + + +def test_delete_prediction_api_key_registration_rest_error(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + 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 = PredictionApiKeyRegistryClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PredictionApiKeyRegistryClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PredictionApiKeyRegistryGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.PredictionApiKeyRegistryGrpcTransport, + transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, + transports.PredictionApiKeyRegistryRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = PredictionApiKeyRegistryClient.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 = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PredictionApiKeyRegistryGrpcTransport, + ) + +def test_prediction_api_key_registry_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PredictionApiKeyRegistryTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_prediction_api_key_registry_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.PredictionApiKeyRegistryTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_prediction_api_key_registration', + 'list_prediction_api_key_registrations', + 'delete_prediction_api_key_registration', + ) + 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_api_key_registry_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.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionApiKeyRegistryTransport( + 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_api_key_registry_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.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.PredictionApiKeyRegistryTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PredictionApiKeyRegistryTransport() + adc.assert_called_once() + + +def test_prediction_api_key_registry_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) + PredictionApiKeyRegistryClient() + 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.PredictionApiKeyRegistryGrpcTransport, + transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, + ], +) +def test_prediction_api_key_registry_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.PredictionApiKeyRegistryGrpcTransport, + transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, + transports.PredictionApiKeyRegistryRestTransport, + ], +) +def test_prediction_api_key_registry_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.PredictionApiKeyRegistryGrpcTransport, grpc_helpers), + (transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_prediction_api_key_registry_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( + "recommendationengine.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="recommendationengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.PredictionApiKeyRegistryGrpcTransport, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport]) +def test_prediction_api_key_registry_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_prediction_api_key_registry_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.PredictionApiKeyRegistryRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_prediction_api_key_registry_host_no_port(transport_name): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://recommendationengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_prediction_api_key_registry_host_with_port(transport_name): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'recommendationengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://recommendationengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_prediction_api_key_registry_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = PredictionApiKeyRegistryClient( + credentials=creds1, + transport=transport_name, + ) + client2 = PredictionApiKeyRegistryClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_prediction_api_key_registration._session + session2 = client2.transport.create_prediction_api_key_registration._session + assert session1 != session2 + session1 = client1.transport.list_prediction_api_key_registrations._session + session2 = client2.transport.list_prediction_api_key_registrations._session + assert session1 != session2 + session1 = client1.transport.delete_prediction_api_key_registration._session + session2 = client2.transport.delete_prediction_api_key_registration._session + assert session1 != session2 +def test_prediction_api_key_registry_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + 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_api_key_registry_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PredictionApiKeyRegistryGrpcAsyncIOTransport( + 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.PredictionApiKeyRegistryGrpcTransport, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport]) +def test_prediction_api_key_registry_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.PredictionApiKeyRegistryGrpcTransport, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport]) +def test_prediction_api_key_registry_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_event_store_path(): + project = "squid" + location = "clam" + catalog = "whelk" + event_store = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) + actual = PredictionApiKeyRegistryClient.event_store_path(project, location, catalog, event_store) + assert expected == actual + + +def test_parse_event_store_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "event_store": "mussel", + } + path = PredictionApiKeyRegistryClient.event_store_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.parse_event_store_path(path) + assert expected == actual + +def test_prediction_api_key_registration_path(): + project = "winkle" + location = "nautilus" + catalog = "scallop" + event_store = "abalone" + prediction_api_key_registration = "squid" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/predictionApiKeyRegistrations/{prediction_api_key_registration}".format(project=project, location=location, catalog=catalog, event_store=event_store, prediction_api_key_registration=prediction_api_key_registration, ) + actual = PredictionApiKeyRegistryClient.prediction_api_key_registration_path(project, location, catalog, event_store, prediction_api_key_registration) + assert expected == actual + + +def test_parse_prediction_api_key_registration_path(): + expected = { + "project": "clam", + "location": "whelk", + "catalog": "octopus", + "event_store": "oyster", + "prediction_api_key_registration": "nudibranch", + } + path = PredictionApiKeyRegistryClient.prediction_api_key_registration_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.parse_prediction_api_key_registration_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = PredictionApiKeyRegistryClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = PredictionApiKeyRegistryClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = PredictionApiKeyRegistryClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = PredictionApiKeyRegistryClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = PredictionApiKeyRegistryClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = PredictionApiKeyRegistryClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = PredictionApiKeyRegistryClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = PredictionApiKeyRegistryClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.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 = PredictionApiKeyRegistryClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = PredictionApiKeyRegistryClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionApiKeyRegistryClient.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.PredictionApiKeyRegistryTransport, '_prep_wrapped_messages') as prep: + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.PredictionApiKeyRegistryTransport, '_prep_wrapped_messages') as prep: + transport_class = PredictionApiKeyRegistryClient.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 = PredictionApiKeyRegistryAsyncClient( + 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 = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PredictionApiKeyRegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = PredictionApiKeyRegistryClient( + 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", [ + (PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport), + (PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport), +]) +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/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py new file mode 100644 index 00000000..21af1fd1 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py @@ -0,0 +1,1967 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.recommendationengine_v1beta1.services.prediction_service import PredictionServiceAsyncClient +from google.cloud.recommendationengine_v1beta1.services.prediction_service import PredictionServiceClient +from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers +from google.cloud.recommendationengine_v1beta1.services.prediction_service import transports +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import common +from google.cloud.recommendationengine_v1beta1.types import prediction_service +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.oauth2 import service_account +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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"), + (PredictionServiceClient, "rest"), +]) +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 == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://recommendationengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.PredictionServiceGrpcTransport, "grpc"), + (transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.PredictionServiceRestTransport, "rest"), +]) +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"), + (PredictionServiceClient, "rest"), +]) +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 == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://recommendationengine.googleapis.com' + ) + + +def test_prediction_service_client_get_transport_class(): + transport = PredictionServiceClient.get_transport_class() + available_transports = [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceRestTransport, + ] + 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"), + (PredictionServiceClient, transports.PredictionServiceRestTransport, "rest"), +]) +@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"), + (PredictionServiceClient, transports.PredictionServiceRestTransport, "rest", "true"), + (PredictionServiceClient, transports.PredictionServiceRestTransport, "rest", "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"), + (PredictionServiceClient, transports.PredictionServiceRestTransport, "rest"), +]) +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), + (PredictionServiceClient, transports.PredictionServiceRestTransport, "rest", None), +]) +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.recommendationengine_v1beta1.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( + "recommendationengine.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="recommendationengine.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( + recommendation_token='recommendation_token_value', + items_missing_in_catalog=['items_missing_in_catalog_value'], + dry_run=True, + next_page_token='next_page_token_value', + ) + 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, pagers.PredictPager) + assert response.recommendation_token == 'recommendation_token_value' + assert response.items_missing_in_catalog == ['items_missing_in_catalog_value'] + assert response.dry_run is True + assert response.next_page_token == 'next_page_token_value' + + +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( + recommendation_token='recommendation_token_value', + items_missing_in_catalog=['items_missing_in_catalog_value'], + dry_run=True, + next_page_token='next_page_token_value', + )) + 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, pagers.PredictAsyncPager) + assert response.recommendation_token == 'recommendation_token_value' + assert response.items_missing_in_catalog == ['items_missing_in_catalog_value'] + assert response.dry_run is True + assert response.next_page_token == 'next_page_token_value' + + +@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.name = 'name_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', + 'name=name_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.name = 'name_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_predict_flattened(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.predict( + name='name_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].user_event + mock_val = gcr_user_event.UserEvent(event_type='event_type_value') + assert arg == mock_val + + +def test_predict_flattened_error(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.predict( + prediction_service.PredictRequest(), + name='name_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + +@pytest.mark.asyncio +async def test_predict_flattened_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(prediction_service.PredictResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.predict( + name='name_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].user_event + mock_val = gcr_user_event.UserEvent(event_type='event_type_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_predict_flattened_error_async(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.predict( + prediction_service.PredictRequest(), + name='name_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + +def test_predict_pager(transport_name: str = "grpc"): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='abc', + ), + prediction_service.PredictResponse( + results=[], + next_page_token='def', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='ghi', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), + ) + pager = client.predict(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, prediction_service.PredictResponse.PredictionResult) + for i in results) +def test_predict_pages(transport_name: str = "grpc"): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='abc', + ), + prediction_service.PredictResponse( + results=[], + next_page_token='def', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='ghi', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + ), + RuntimeError, + ) + pages = list(client.predict(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_predict_async_pager(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='abc', + ), + prediction_service.PredictResponse( + results=[], + next_page_token='def', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='ghi', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.predict(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, prediction_service.PredictResponse.PredictionResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_predict_async_pages(): + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.predict), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='abc', + ), + prediction_service.PredictResponse( + results=[], + next_page_token='def', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='ghi', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.predict(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", [ + prediction_service.PredictRequest, + dict, +]) +def test_predict_rest(request_type): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/placements/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = prediction_service.PredictResponse( + recommendation_token='recommendation_token_value', + items_missing_in_catalog=['items_missing_in_catalog_value'], + dry_run=True, + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = prediction_service.PredictResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.predict(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.PredictPager) + assert response.recommendation_token == 'recommendation_token_value' + assert response.items_missing_in_catalog == ['items_missing_in_catalog_value'] + assert response.dry_run is True + assert response.next_page_token == 'next_page_token_value' + + +def test_predict_rest_required_fields(request_type=prediction_service.PredictRequest): + transport_class = transports.PredictionServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).predict._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).predict._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = prediction_service.PredictResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = prediction_service.PredictResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.predict(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_predict_rest_unset_required_fields(): + transport = transports.PredictionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.predict._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "userEvent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_predict_rest_interceptors(null_interceptor): + transport = transports.PredictionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.PredictionServiceRestInterceptor(), + ) + client = PredictionServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.PredictionServiceRestInterceptor, "post_predict") as post, \ + mock.patch.object(transports.PredictionServiceRestInterceptor, "pre_predict") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = prediction_service.PredictRequest.pb(prediction_service.PredictRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = prediction_service.PredictResponse.to_json(prediction_service.PredictResponse()) + + request = prediction_service.PredictRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = prediction_service.PredictResponse() + + client.predict(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_predict_rest_bad_request(transport: str = 'rest', request_type=prediction_service.PredictRequest): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/placements/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.predict(request) + + +def test_predict_rest_flattened(): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = prediction_service.PredictResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/placements/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = prediction_service.PredictResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.predict(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{name=projects/*/locations/*/catalogs/*/eventStores/*/placements/*}:predict" % client.transport._host, args[1]) + + +def test_predict_rest_flattened_error(transport: str = 'rest'): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.predict( + prediction_service.PredictRequest(), + name='name_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + +def test_predict_rest_pager(transport: str = 'rest'): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='abc', + ), + prediction_service.PredictResponse( + results=[], + next_page_token='def', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + ], + next_page_token='ghi', + ), + prediction_service.PredictResponse( + results=[ + prediction_service.PredictResponse.PredictionResult(), + prediction_service.PredictResponse.PredictionResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(prediction_service.PredictResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'name': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4/placements/sample5'} + + pager = client.predict(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, prediction_service.PredictResponse.PredictionResult) + for i in results) + + pages = list(client.predict(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.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, + transports.PredictionServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = 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.recommendationengine_v1beta1.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.recommendationengine_v1beta1.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.recommendationengine_v1beta1.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( + "recommendationengine.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="recommendationengine.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 + ) + +def test_prediction_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.PredictionServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_prediction_service_host_no_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://recommendationengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_prediction_service_host_with_port(transport_name): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'recommendationengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://recommendationengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_prediction_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = PredictionServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = PredictionServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.predict._session + session2 = client2.transport.predict._session + assert session1 != session2 +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_placement_path(): + project = "squid" + location = "clam" + catalog = "whelk" + event_store = "octopus" + placement = "oyster" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/placements/{placement}".format(project=project, location=location, catalog=catalog, event_store=event_store, placement=placement, ) + actual = PredictionServiceClient.placement_path(project, location, catalog, event_store, placement) + assert expected == actual + + +def test_parse_placement_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "catalog": "mussel", + "event_store": "winkle", + "placement": "nautilus", + } + path = PredictionServiceClient.placement_path(**expected) + + # Check that the path construction is reversible. + actual = PredictionServiceClient.parse_placement_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 = { + "rest": "_session", + "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 = [ + 'rest', + '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/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py new file mode 100644 index 00000000..a61482d2 --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py @@ -0,0 +1,4013 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.recommendationengine_v1beta1.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.recommendationengine_v1beta1.services.user_event_service import UserEventServiceClient +from google.cloud.recommendationengine_v1beta1.services.user_event_service import pagers +from google.cloud.recommendationengine_v1beta1.services.user_event_service import transports +from google.cloud.recommendationengine_v1beta1.types import catalog +from google.cloud.recommendationengine_v1beta1.types import common +from google.cloud.recommendationengine_v1beta1.types import import_ +from google.cloud.recommendationengine_v1beta1.types import user_event +from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event +from google.cloud.recommendationengine_v1beta1.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 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 UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), + (UserEventServiceClient, "rest"), +]) +def test_user_event_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://recommendationengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.UserEventServiceRestTransport, "rest"), +]) +def test_user_event_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), + (UserEventServiceClient, "rest"), +]) +def test_user_event_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://recommendationengine.googleapis.com' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceRestTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "true"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), +]) +def test_user_event_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", None), +]) +def test_user_event_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.recommendationengine_v1beta1.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( + "recommendationengine.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="recommendationengine.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 = gcr_user_event.UserEvent( + event_type='event_type_value', + event_source=gcr_user_event.UserEvent.EventSource.AUTOML, + ) + 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, gcr_user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.event_source == gcr_user_event.UserEvent.EventSource.AUTOML + + +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(gcr_user_event.UserEvent( + event_type='event_type_value', + event_source=gcr_user_event.UserEvent.EventSource.AUTOML, + )) + 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, gcr_user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.event_source == gcr_user_event.UserEvent.EventSource.AUTOML + + +@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 = gcr_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(gcr_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'] + + +def test_write_user_event_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_user_event.UserEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.write_user_event( + parent='parent_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_event + mock_val = gcr_user_event.UserEvent(event_type='event_type_value') + assert arg == mock_val + + +def test_write_user_event_flattened_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.write_user_event( + user_event_service.WriteUserEventRequest(), + parent='parent_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + +@pytest.mark.asyncio +async def test_write_user_event_flattened_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcr_user_event.UserEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcr_user_event.UserEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.write_user_event( + parent='parent_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_event + mock_val = gcr_user_event.UserEvent(event_type='event_type_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_write_user_event_flattened_error_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.write_user_event( + user_event_service.WriteUserEventRequest(), + parent='parent_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + +@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'] + + +def test_collect_user_event_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.collect_user_event( + parent='parent_value', + user_event='user_event_value', + uri='uri_value', + ets=332, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_event + mock_val = 'user_event_value' + assert arg == mock_val + arg = args[0].uri + mock_val = 'uri_value' + assert arg == mock_val + arg = args[0].ets + mock_val = 332 + assert arg == mock_val + + +def test_collect_user_event_flattened_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.collect_user_event( + user_event_service.CollectUserEventRequest(), + parent='parent_value', + user_event='user_event_value', + uri='uri_value', + ets=332, + ) + +@pytest.mark.asyncio +async def test_collect_user_event_flattened_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.collect_user_event( + parent='parent_value', + user_event='user_event_value', + uri='uri_value', + ets=332, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user_event + mock_val = 'user_event_value' + assert arg == mock_val + arg = args[0].uri + mock_val = 'uri_value' + assert arg == mock_val + arg = args[0].ets + mock_val = 332 + assert arg == mock_val + +@pytest.mark.asyncio +async def test_collect_user_event_flattened_error_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.collect_user_event( + user_event_service.CollectUserEventRequest(), + parent='parent_value', + user_event='user_event_value', + uri='uri_value', + ets=332, + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.ListUserEventsRequest, + dict, +]) +def test_list_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.list_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event_service.ListUserEventsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_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.ListUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserEventsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_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.list_user_events), + '__call__') as call: + client.list_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.ListUserEventsRequest() + +@pytest.mark.asyncio +async def test_list_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.ListUserEventsRequest): + 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.list_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event_service.ListUserEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_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.ListUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserEventsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_user_events_async_from_dict(): + await test_list_user_events_async(request_type=dict) + + +def test_list_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.ListUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + call.return_value = user_event_service.ListUserEventsResponse() + client.list_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_list_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.ListUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event_service.ListUserEventsResponse()) + await client.list_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_list_user_events_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event_service.ListUserEventsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_user_events( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + + +def test_list_user_events_flattened_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_user_events( + user_event_service.ListUserEventsRequest(), + parent='parent_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_list_user_events_flattened_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event_service.ListUserEventsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event_service.ListUserEventsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_user_events( + parent='parent_value', + filter='filter_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_user_events_flattened_error_async(): + client = UserEventServiceAsyncClient( + credentials=ga_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_user_events( + user_event_service.ListUserEventsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_user_events_pager(transport_name: str = "grpc"): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + user_event.UserEvent(), + ], + next_page_token='abc', + ), + user_event_service.ListUserEventsResponse( + user_events=[], + next_page_token='def', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + ], + next_page_token='ghi', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_user_events(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, user_event.UserEvent) + for i in results) +def test_list_user_events_pages(transport_name: str = "grpc"): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + user_event.UserEvent(), + ], + next_page_token='abc', + ), + user_event_service.ListUserEventsResponse( + user_events=[], + next_page_token='def', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + ], + next_page_token='ghi', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_user_events(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_user_events_async_pager(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + user_event.UserEvent(), + ], + next_page_token='abc', + ), + user_event_service.ListUserEventsResponse( + user_events=[], + next_page_token='def', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + ], + next_page_token='ghi', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_user_events(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, user_event.UserEvent) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_user_events_async_pages(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_user_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + user_event.UserEvent(), + ], + next_page_token='abc', + ), + user_event_service.ListUserEventsResponse( + user_events=[], + next_page_token='def', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + ], + next_page_token='ghi', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_user_events(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", [ + user_event_service.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] == user_event_service.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] == user_event_service.PurgeUserEventsRequest() + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=user_event_service.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] == user_event_service.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 = user_event_service.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 = user_event_service.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'] + + +def test_purge_user_events_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__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.purge_user_events( + parent='parent_value', + filter='filter_value', + force=True, + ) + + # Establish that the 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].filter + mock_val = 'filter_value' + assert arg == mock_val + arg = args[0].force + mock_val = True + assert arg == mock_val + + +def test_purge_user_events_flattened_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.purge_user_events( + user_event_service.PurgeUserEventsRequest(), + parent='parent_value', + filter='filter_value', + force=True, + ) + +@pytest.mark.asyncio +async def test_purge_user_events_flattened_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__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.purge_user_events( + parent='parent_value', + filter='filter_value', + force=True, + ) + + # Establish that 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].filter + mock_val = 'filter_value' + assert arg == mock_val + arg = args[0].force + mock_val = True + assert arg == mock_val + +@pytest.mark.asyncio +async def test_purge_user_events_flattened_error_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.purge_user_events( + user_event_service.PurgeUserEventsRequest(), + parent='parent_value', + filter='filter_value', + force=True, + ) + + +@pytest.mark.parametrize("request_type", [ + import_.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_.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_.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_.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_.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_.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_.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'] + + +def test_import_user_events_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.import_user_events( + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + # Establish that the 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].request_id + mock_val = 'request_id_value' + assert arg == mock_val + arg = args[0].input_config + mock_val = import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) + assert arg == mock_val + arg = args[0].errors_config + mock_val = import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') + assert arg == mock_val + + +def test_import_user_events_flattened_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_user_events( + import_.ImportUserEventsRequest(), + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + +@pytest.mark.asyncio +async def test_import_user_events_flattened_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__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.import_user_events( + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + # Establish that 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].request_id + mock_val = 'request_id_value' + assert arg == mock_val + arg = args[0].input_config + mock_val = import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])) + assert arg == mock_val + arg = args[0].errors_config + mock_val = import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_import_user_events_flattened_error_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.import_user_events( + import_.ImportUserEventsRequest(), + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request_init["user_event"] = {'event_type': 'event_type_value', 'user_info': {'visitor_id': 'visitor_id_value', 'user_id': 'user_id_value', 'ip_address': 'ip_address_value', 'user_agent': 'user_agent_value', 'direct_user_request': True}, 'event_detail': {'uri': 'uri_value', 'referrer_uri': 'referrer_uri_value', 'page_view_id': 'page_view_id_value', 'experiment_ids': ['experiment_ids_value1', 'experiment_ids_value2'], 'recommendation_token': 'recommendation_token_value', 'event_attributes': {'categorical_features': {}, 'numerical_features': {}}}, 'product_event_detail': {'search_query': 'search_query_value', 'page_categories': [{'categories': ['categories_value1', 'categories_value2']}], 'product_details': [{'id': 'id_value', 'currency_code': 'currency_code_value', 'original_price': 0.1479, 'display_price': 0.1384, 'stock_state': 1, 'quantity': 895, 'available_quantity': 1919, 'item_attributes': {}}], 'list_id': 'list_id_value', 'cart_id': 'cart_id_value', 'purchase_transaction': {'id': 'id_value', 'revenue': 0.762, 'taxes': {}, 'costs': {}, 'currency_code': 'currency_code_value'}}, 'event_time': {'seconds': 751, 'nanos': 543}, 'event_source': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcr_user_event.UserEvent( + event_type='event_type_value', + event_source=gcr_user_event.UserEvent.EventSource.AUTOML, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcr_user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.write_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcr_user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.event_source == gcr_user_event.UserEvent.EventSource.AUTOML + + +def test_write_user_event_rest_required_fields(request_type=user_event_service.WriteUserEventRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcr_user_event.UserEvent() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = gcr_user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.write_user_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_write_user_event_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.write_user_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "userEvent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_write_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "post_write_user_event") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_write_user_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.WriteUserEventRequest.pb(user_event_service.WriteUserEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcr_user_event.UserEvent.to_json(gcr_user_event.UserEvent()) + + request = user_event_service.WriteUserEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcr_user_event.UserEvent() + + client.write_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_write_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request_init["user_event"] = {'event_type': 'event_type_value', 'user_info': {'visitor_id': 'visitor_id_value', 'user_id': 'user_id_value', 'ip_address': 'ip_address_value', 'user_agent': 'user_agent_value', 'direct_user_request': True}, 'event_detail': {'uri': 'uri_value', 'referrer_uri': 'referrer_uri_value', 'page_view_id': 'page_view_id_value', 'experiment_ids': ['experiment_ids_value1', 'experiment_ids_value2'], 'recommendation_token': 'recommendation_token_value', 'event_attributes': {'categorical_features': {}, 'numerical_features': {}}}, 'product_event_detail': {'search_query': 'search_query_value', 'page_categories': [{'categories': ['categories_value1', 'categories_value2']}], 'product_details': [{'id': 'id_value', 'currency_code': 'currency_code_value', 'original_price': 0.1479, 'display_price': 0.1384, 'stock_state': 1, 'quantity': 895, 'available_quantity': 1919, 'item_attributes': {}}], 'list_id': 'list_id_value', 'cart_id': 'cart_id_value', 'purchase_transaction': {'id': 'id_value', 'revenue': 0.762, 'taxes': {}, 'costs': {}, 'currency_code': 'currency_code_value'}}, 'event_time': {'seconds': 751, 'nanos': 543}, 'event_source': 1} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.write_user_event(request) + + +def test_write_user_event_rest_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcr_user_event.UserEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcr_user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.write_user_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:write" % client.transport._host, args[1]) + + +def test_write_user_event_rest_flattened_error(transport: str = 'rest'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.write_user_event( + user_event_service.WriteUserEventRequest(), + parent='parent_value', + user_event=gcr_user_event.UserEvent(event_type='event_type_value'), + ) + + +def test_write_user_event_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.collect_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_rest_required_fields(request_type=user_event_service.CollectUserEventRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["user_event"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "userEvent" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "userEvent" in jsonified_request + assert jsonified_request["userEvent"] == request_init["user_event"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["userEvent"] = 'user_event_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("ets", "uri", "user_event", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "userEvent" in jsonified_request + assert jsonified_request["userEvent"] == 'user_event_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.collect_user_event(request) + + expected_params = [ + ( + "userEvent", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_collect_user_event_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.collect_user_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("ets", "uri", "userEvent", )) & set(("parent", "userEvent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_collect_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "post_collect_user_event") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_collect_user_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.CollectUserEventRequest.pb(user_event_service.CollectUserEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(httpbody_pb2.HttpBody()) + + request = user_event_service.CollectUserEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = httpbody_pb2.HttpBody() + + client.collect_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_collect_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.collect_user_event(request) + + +def test_collect_user_event_rest_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user_event='user_event_value', + uri='uri_value', + ets=332, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.collect_user_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:collect" % client.transport._host, args[1]) + + +def test_collect_user_event_rest_flattened_error(transport: str = 'rest'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.collect_user_event( + user_event_service.CollectUserEventRequest(), + parent='parent_value', + user_event='user_event_value', + uri='uri_value', + ets=332, + ) + + +def test_collect_user_event_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.ListUserEventsRequest, + dict, +]) +def test_list_user_events_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = user_event_service.ListUserEventsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = user_event_service.ListUserEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_user_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUserEventsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_user_events_rest_required_fields(request_type=user_event_service.ListUserEventsRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_user_events._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = user_event_service.ListUserEventsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = user_event_service.ListUserEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_user_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_user_events_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_user_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "post_list_user_events") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_list_user_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.ListUserEventsRequest.pb(user_event_service.ListUserEventsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = user_event_service.ListUserEventsResponse.to_json(user_event_service.ListUserEventsResponse()) + + request = user_event_service.ListUserEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user_event_service.ListUserEventsResponse() + + client.list_user_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_user_events_rest_bad_request(transport: str = 'rest', request_type=user_event_service.ListUserEventsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_user_events(request) + + +def test_list_user_events_rest_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = user_event_service.ListUserEventsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + filter='filter_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = user_event_service.ListUserEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_user_events(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents" % client.transport._host, args[1]) + + +def test_list_user_events_rest_flattened_error(transport: str = 'rest'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_user_events( + user_event_service.ListUserEventsRequest(), + parent='parent_value', + filter='filter_value', + ) + + +def test_list_user_events_rest_pager(transport: str = 'rest'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + user_event.UserEvent(), + ], + next_page_token='abc', + ), + user_event_service.ListUserEventsResponse( + user_events=[], + next_page_token='def', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + ], + next_page_token='ghi', + ), + user_event_service.ListUserEventsResponse( + user_events=[ + user_event.UserEvent(), + user_event.UserEvent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(user_event_service.ListUserEventsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + + pager = client.list_user_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, user_event.UserEvent) + for i in results) + + pages = list(client.list_user_events(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + user_event_service.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.purge_user_events(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_purge_user_events_rest_required_fields(request_type=user_event_service.PurgeUserEventsRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["filter"] = 'filter_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "filter" in jsonified_request + assert jsonified_request["filter"] == 'filter_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.purge_user_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_purge_user_events_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.purge_user_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "filter", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "post_purge_user_events") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_purge_user_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.PurgeUserEventsRequest.pb(user_event_service.PurgeUserEventsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = user_event_service.PurgeUserEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.purge_user_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_purge_user_events_rest_bad_request(transport: str = 'rest', request_type=user_event_service.PurgeUserEventsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.purge_user_events(request) + + +def test_purge_user_events_rest_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + filter='filter_value', + force=True, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.purge_user_events(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:purge" % client.transport._host, args[1]) + + +def test_purge_user_events_rest_flattened_error(transport: str = 'rest'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.purge_user_events( + user_event_service.PurgeUserEventsRequest(), + parent='parent_value', + filter='filter_value', + force=True, + ) + + +def test_purge_user_events_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + import_.ImportUserEventsRequest, + dict, +]) +def test_import_user_events_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.import_user_events(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_import_user_events_rest_required_fields(request_type=import_.ImportUserEventsRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.import_user_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_user_events_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_user_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "inputConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "post_import_user_events") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_import_user_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_.ImportUserEventsRequest.pb(import_.ImportUserEventsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = import_.ImportUserEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_user_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_user_events_rest_bad_request(transport: str = 'rest', request_type=import_.ImportUserEventsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.import_user_events(request) + + +def test_import_user_events_rest_flattened(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/catalogs/sample3/eventStores/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.import_user_events(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta1/{parent=projects/*/locations/*/catalogs/*/eventStores/*}/userEvents:import" % client.transport._host, args[1]) + + +def test_import_user_events_rest_flattened_error(transport: str = 'rest'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_user_events( + import_.ImportUserEventsRequest(), + parent='parent_value', + request_id='request_id_value', + input_config=import_.InputConfig(catalog_inline_source=import_.CatalogInlineSource(catalog_items=[catalog.CatalogItem(id='id_value')])), + errors_config=import_.ImportErrorsConfig(gcs_prefix='gcs_prefix_value'), + ) + + +def test_import_user_events_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.recommendationengine_v1beta1.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', + 'list_user_events', + 'purge_user_events', + 'import_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.recommendationengine_v1beta1.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.recommendationengine_v1beta1.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( + "recommendationengine.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="recommendationengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_user_event_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.UserEventServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_user_event_service_rest_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'recommendationengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://recommendationengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='recommendationengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'recommendationengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://recommendationengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_user_event_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = UserEventServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = UserEventServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.write_user_event._session + session2 = client2.transport.write_user_event._session + assert session1 != session2 + session1 = client1.transport.collect_user_event._session + session2 = client2.transport.collect_user_event._session + assert session1 != session2 + session1 = client1.transport.list_user_events._session + session2 = client2.transport.list_user_events._session + assert session1 != session2 + session1 = client1.transport.purge_user_events._session + session2 = client2.transport.purge_user_events._session + assert session1 != session2 + session1 = client1.transport.import_user_events._session + session2 = client2.transport.import_user_events._session + assert session1 != session2 +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_event_store_path(): + project = "squid" + location = "clam" + catalog = "whelk" + event_store = "octopus" + expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format(project=project, location=location, catalog=catalog, event_store=event_store, ) + actual = UserEventServiceClient.event_store_path(project, location, catalog, event_store) + assert expected == actual + + +def test_parse_event_store_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "catalog": "cuttlefish", + "event_store": "mussel", + } + path = UserEventServiceClient.event_store_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_event_store_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + 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": "nautilus", + } + 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 = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + 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 = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + 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 = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + 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 = "oyster" + location = "nudibranch" + 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": "cuttlefish", + "location": "mussel", + } + 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 = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + )