diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml new file mode 100644 index 00000000..da616c91 --- /dev/null +++ b/.github/.OwlBot.lock.yaml @@ -0,0 +1,3 @@ +docker: + image: gcr.io/repo-automation-bots/owlbot-python:latest + digest: sha256:c66ba3c8d7bc8566f47df841f98cd0097b28fff0b1864c86f5817f4c8c3e8600 diff --git a/.github/.OwlBot.yaml b/.github/.OwlBot.yaml new file mode 100644 index 00000000..cfdce680 --- /dev/null +++ b/.github/.OwlBot.yaml @@ -0,0 +1,26 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +docker: + image: gcr.io/repo-automation-bots/owlbot-python:latest + +deep-remove-regex: + - /owl-bot-staging + +deep-copy-regex: + - source: /google/cloud/recommendationengine/(v.*)/.*-py/(.*) + dest: /owl-bot-staging/$1/$2 + +begin-after-commit-hash: 107ed1217b5e87048263f52cd3911d5f851aca7e + diff --git a/.github/header-checker-lint.yml b/.github/header-checker-lint.yml index fc281c05..6fe78aa7 100644 --- a/.github/header-checker-lint.yml +++ b/.github/header-checker-lint.yml @@ -1,6 +1,6 @@ {"allowedCopyrightHolders": ["Google LLC"], "allowedLicenses": ["Apache-2.0", "MIT", "BSD-3"], - "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt"], + "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt", "**/__init__.py", "samples/**/constraints.txt", "samples/**/constraints-test.txt"], "sourceFileExtensions": [ "ts", "js", diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 9e0a0a49..225f6840 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -26,7 +26,7 @@ python3 -m pip install --upgrade twine wheel setuptools export PYTHONUNBUFFERED=1 # Move into the package, build the distribution and upload. -TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google_cloud_pypi_password") +TWINE_PASSWORD=$(cat "${KOKORO_GFILE_DIR}/secret_manager/google-cloud-pypi-token") cd github/python-recommendations-ai python3 setup.py sdist bdist_wheel -twine upload --username gcloudpypi --password "${TWINE_PASSWORD}" dist/* +twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/* diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index e260f187..503ddb75 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,18 +23,8 @@ env_vars: { value: "github/python-recommendations-ai/.kokoro/release.sh" } -# Fetch PyPI password -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "google_cloud_pypi_password" - } - } -} - # Tokens needed to report release status back to GitHub env_vars: { key: "SECRET_MANAGER_KEYS" - value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" -} \ No newline at end of file + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem,google-cloud-pypi-token" +} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 32302e48..4f00c7cf 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,3 +1,17 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: @@ -12,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.0 + rev: 3.9.2 hooks: - id: flake8 diff --git a/.repo-metadata.json b/.repo-metadata.json index 577ad250..165ca134 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -6,6 +6,7 @@ "issue_tracker": "", "release_level": "beta", "language": "python", + "library_type": "GAPIC_AUTO", "repo": "googleapis/python-recommendations-ai", "distribution_name": "google-cloud-recommendations-ai", "api_id": "recommendationengine.googleapis.com" diff --git a/CHANGELOG.md b/CHANGELOG.md index 3732c832..91cd93a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +### [0.2.1](https://www.github.com/googleapis/python-recommendations-ai/compare/v0.2.0...v0.2.1) (2021-05-28) + + +### Bug Fixes + +* **deps:** add packaging requirement ([#46](https://www.github.com/googleapis/python-recommendations-ai/issues/46)) ([d2eb28f](https://www.github.com/googleapis/python-recommendations-ai/commit/d2eb28fdc016de1b9f82e46f36b8bf8c8bb7edbd)) + ## [0.2.0](https://www.github.com/googleapis/python-recommendations-ai/compare/v0.1.0...v0.2.0) (2021-03-29) diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 84501494..f4b63c51 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -160,21 +160,7 @@ Running System Tests auth settings and change some configuration in your project to run all the tests. -- System tests will be run against an actual project and - so you'll need to provide some environment variables to facilitate - authentication to your project: - - - ``GOOGLE_APPLICATION_CREDENTIALS``: The path to a JSON key file; - Such a file can be downloaded directly from the developer's console by clicking - "Generate new JSON key". See private key - `docs `__ - for more details. - -- Once you have downloaded your json keys, set the environment variable - ``GOOGLE_APPLICATION_CREDENTIALS`` to the absolute path of the json file:: - - $ export GOOGLE_APPLICATION_CREDENTIALS="/Users//path/to/app_credentials.json" - +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__. ************* Test Coverage diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..8b58ae9c --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# Security Policy + +To report a security issue, please use [g.co/vulnz](https://g.co/vulnz). + +The Google Security Team will respond within 5 working days of your report on g.co/vulnz. + +We use g.co/vulnz for our intake, and do coordination and disclosure here using GitHub Security Advisory to privately discuss and fix the issue. diff --git a/docs/_static/custom.css b/docs/_static/custom.css index bcd37bbd..b0a29546 100644 --- a/docs/_static/custom.css +++ b/docs/_static/custom.css @@ -1,9 +1,20 @@ div#python2-eol { border-color: red; border-width: medium; -} +} /* Ensure minimum width for 'Parameters' / 'Returns' column */ dl.field-list > dt { min-width: 100px } + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/docs/conf.py b/docs/conf.py index f54b8f1c..463c5670 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,4 +1,17 @@ # -*- coding: utf-8 -*- +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. # # google-cloud-recommendations-ai documentation build configuration file # @@ -350,6 +363,7 @@ "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), "grpc": ("https://grpc.github.io/grpc/python/", None), "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), } diff --git a/docs/multiprocessing.rst b/docs/multiprocessing.rst index 1cb29d4c..536d17b2 100644 --- a/docs/multiprocessing.rst +++ b/docs/multiprocessing.rst @@ -1,7 +1,7 @@ .. note:: - Because this client uses :mod:`grpcio` library, it is safe to + Because this client uses :mod:`grpc` library, it is safe to share instances across threads. In multiprocessing scenarios, the best practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.Pool` or + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or :class:`multiprocessing.Process`. diff --git a/docs/recommendationengine_v1beta1/catalog_service.rst b/docs/recommendationengine_v1beta1/catalog_service.rst index 7d05e892..48f7c814 100644 --- a/docs/recommendationengine_v1beta1/catalog_service.rst +++ b/docs/recommendationengine_v1beta1/catalog_service.rst @@ -5,7 +5,6 @@ CatalogService :members: :inherited-members: - .. automodule:: google.cloud.recommendationengine_v1beta1.services.catalog_service.pagers :members: :inherited-members: diff --git a/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst b/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst index 059e2e7d..74874c31 100644 --- a/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst +++ b/docs/recommendationengine_v1beta1/prediction_api_key_registry.rst @@ -5,7 +5,6 @@ PredictionApiKeyRegistry :members: :inherited-members: - .. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.pagers :members: :inherited-members: diff --git a/docs/recommendationengine_v1beta1/prediction_service.rst b/docs/recommendationengine_v1beta1/prediction_service.rst index 93a16f30..7d2fc56d 100644 --- a/docs/recommendationengine_v1beta1/prediction_service.rst +++ b/docs/recommendationengine_v1beta1/prediction_service.rst @@ -5,7 +5,6 @@ PredictionService :members: :inherited-members: - .. automodule:: google.cloud.recommendationengine_v1beta1.services.prediction_service.pagers :members: :inherited-members: diff --git a/docs/recommendationengine_v1beta1/user_event_service.rst b/docs/recommendationengine_v1beta1/user_event_service.rst index 665351c9..728ec7e9 100644 --- a/docs/recommendationengine_v1beta1/user_event_service.rst +++ b/docs/recommendationengine_v1beta1/user_event_service.rst @@ -5,7 +5,6 @@ UserEventService :members: :inherited-members: - .. automodule:: google.cloud.recommendationengine_v1beta1.services.user_event_service.pagers :members: :inherited-members: diff --git a/google/cloud/recommendationengine/__init__.py b/google/cloud/recommendationengine/__init__.py index 80454bde..dd05f669 100644 --- a/google/cloud/recommendationengine/__init__.py +++ b/google/cloud/recommendationengine/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,30 +14,31 @@ # limitations under the License. # -from google.cloud.recommendationengine_v1beta1.services.catalog_service.async_client import ( - CatalogServiceAsyncClient, -) from google.cloud.recommendationengine_v1beta1.services.catalog_service.client import ( CatalogServiceClient, ) -from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.async_client import ( - PredictionApiKeyRegistryAsyncClient, +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_service.async_client import ( - PredictionServiceAsyncClient, +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.user_event_service.async_client import ( - UserEventServiceAsyncClient, +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 @@ -138,20 +138,26 @@ ) __all__ = ( - "CatalogInlineSource", - "CatalogItem", - "CatalogServiceAsyncClient", "CatalogServiceClient", - "CollectUserEventRequest", + "CatalogServiceAsyncClient", + "PredictionApiKeyRegistryClient", + "PredictionApiKeyRegistryAsyncClient", + "PredictionServiceClient", + "PredictionServiceAsyncClient", + "UserEventServiceClient", + "UserEventServiceAsyncClient", + "CatalogItem", + "Image", + "ProductCatalogItem", "CreateCatalogItemRequest", - "CreatePredictionApiKeyRegistrationRequest", "DeleteCatalogItemRequest", - "DeletePredictionApiKeyRegistrationRequest", - "EventDetail", + "GetCatalogItemRequest", + "ListCatalogItemsRequest", + "ListCatalogItemsResponse", + "UpdateCatalogItemRequest", "FeatureMap", + "CatalogInlineSource", "GcsSource", - "GetCatalogItemRequest", - "Image", "ImportCatalogItemsRequest", "ImportCatalogItemsResponse", "ImportErrorsConfig", @@ -159,32 +165,26 @@ "ImportUserEventsRequest", "ImportUserEventsResponse", "InputConfig", - "ListCatalogItemsRequest", - "ListCatalogItemsResponse", + "UserEventImportSummary", + "UserEventInlineSource", + "CreatePredictionApiKeyRegistrationRequest", + "DeletePredictionApiKeyRegistrationRequest", "ListPredictionApiKeyRegistrationsRequest", "ListPredictionApiKeyRegistrationsResponse", - "ListUserEventsRequest", - "ListUserEventsResponse", + "PredictionApiKeyRegistration", "PredictRequest", "PredictResponse", - "PredictionApiKeyRegistration", - "PredictionApiKeyRegistryAsyncClient", - "PredictionApiKeyRegistryClient", - "PredictionServiceAsyncClient", - "PredictionServiceClient", - "ProductCatalogItem", + "EventDetail", "ProductDetail", "ProductEventDetail", "PurchaseTransaction", + "UserEvent", + "UserInfo", + "CollectUserEventRequest", + "ListUserEventsRequest", + "ListUserEventsResponse", "PurgeUserEventsMetadata", "PurgeUserEventsRequest", "PurgeUserEventsResponse", - "UpdateCatalogItemRequest", - "UserEvent", - "UserEventImportSummary", - "UserEventInlineSource", - "UserEventServiceAsyncClient", - "UserEventServiceClient", - "UserInfo", "WriteUserEventRequest", ) diff --git a/google/cloud/recommendationengine/py.typed b/google/cloud/recommendationengine/py.typed index cc6dbe67..41689a36 100644 --- a/google/cloud/recommendationengine/py.typed +++ b/google/cloud/recommendationengine/py.typed @@ -1,2 +1,2 @@ # Marker file for PEP 561. -# The google-cloud-recommendationengine package uses inline types. +# The google-cloud-recommendations-ai package uses inline types. diff --git a/google/cloud/recommendationengine_v1beta1/__init__.py b/google/cloud/recommendationengine_v1beta1/__init__.py index 60f9ea99..f29eede5 100644 --- a/google/cloud/recommendationengine_v1beta1/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,9 +15,14 @@ # 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 @@ -69,8 +73,11 @@ from .types.user_event_service import PurgeUserEventsResponse from .types.user_event_service import WriteUserEventRequest - __all__ = ( + "CatalogServiceAsyncClient", + "PredictionApiKeyRegistryAsyncClient", + "PredictionServiceAsyncClient", + "UserEventServiceAsyncClient", "CatalogInlineSource", "CatalogItem", "CatalogServiceClient", @@ -113,7 +120,7 @@ "UserEvent", "UserEventImportSummary", "UserEventInlineSource", + "UserEventServiceClient", "UserInfo", "WriteUserEventRequest", - "UserEventServiceClient", ) diff --git a/google/cloud/recommendationengine_v1beta1/gapic_metadata.json b/google/cloud/recommendationengine_v1beta1/gapic_metadata.json new file mode 100644 index 00000000..b5ae877c --- /dev/null +++ b/google/cloud/recommendationengine_v1beta1/gapic_metadata.json @@ -0,0 +1,215 @@ + { + "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" + ] + } + } + } + } + }, + "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" + ] + } + } + } + } + }, + "PredictionService": { + "clients": { + "grpc": { + "libraryClient": "PredictionServiceClient", + "rpcs": { + "Predict": { + "methods": [ + "predict" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PredictionServiceAsyncClient", + "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" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/recommendationengine_v1beta1/py.typed b/google/cloud/recommendationengine_v1beta1/py.typed index cc6dbe67..41689a36 100644 --- a/google/cloud/recommendationengine_v1beta1/py.typed +++ b/google/cloud/recommendationengine_v1beta1/py.typed @@ -1,2 +1,2 @@ # Marker file for PEP 561. -# The google-cloud-recommendationengine package uses inline types. +# The google-cloud-recommendations-ai package uses inline types. diff --git a/google/cloud/recommendationengine_v1beta1/services/__init__.py b/google/cloud/recommendationengine_v1beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/recommendationengine_v1beta1/services/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py index d5e1eecf..12f0071a 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import CatalogServiceClient from .async_client import CatalogServiceAsyncClient diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py index 611957fd..3b3bb449 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -35,8 +33,7 @@ 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 as field_mask # type: ignore - +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 @@ -61,24 +58,20 @@ class CatalogServiceAsyncClient: 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 @@ -86,7 +79,8 @@ class CatalogServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -101,7 +95,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -118,7 +112,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> CatalogServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: CatalogServiceTransport: The transport used by the client instance. @@ -132,12 +126,12 @@ def transport(self) -> CatalogServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, CatalogServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the catalog service client. + """Instantiates the catalog service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -169,7 +163,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = CatalogServiceClient( credentials=credentials, transport=transport, @@ -195,7 +188,7 @@ async def create_catalog_item( CreateCatalogItem method. parent (:class:`str`): Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog`` + ``projects/*/locations/global/catalogs/default_catalog``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -205,7 +198,6 @@ async def create_catalog_item( 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. @@ -232,7 +224,6 @@ async def create_catalog_item( # 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: @@ -247,7 +238,8 @@ async def create_catalog_item( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -284,12 +276,11 @@ async def get_catalog_item( method. name (:class:`str`): Required. Full resource name of catalog item, such as - ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_id`` + ``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. @@ -316,7 +307,6 @@ async def get_catalog_item( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -329,7 +319,8 @@ async def get_catalog_item( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -367,7 +358,7 @@ async def list_catalog_items( method. parent (:class:`str`): Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog`` + ``projects/*/locations/global/catalogs/default_catalog``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -379,7 +370,6 @@ async def list_catalog_items( 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. @@ -409,7 +399,6 @@ async def list_catalog_items( # 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: @@ -424,7 +413,8 @@ async def list_catalog_items( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -456,7 +446,7 @@ async def update_catalog_item( *, name: str = None, catalog_item: catalog.CatalogItem = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -490,7 +480,6 @@ async def update_catalog_item( 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. @@ -517,7 +506,6 @@ async def update_catalog_item( # 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: @@ -534,7 +522,8 @@ async def update_catalog_item( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -571,12 +560,11 @@ async def delete_catalog_item( 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`` + ``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. @@ -597,7 +585,6 @@ async def delete_catalog_item( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -610,7 +597,8 @@ async def delete_catalog_item( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -654,7 +642,7 @@ async def import_catalog_items( The request object. Request message for Import methods. parent (:class:`str`): Required. - "projects/1234/locations/global/catalogs/default_catalog" + ``projects/1234/locations/global/catalogs/default_catalog`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -686,7 +674,6 @@ async def import_catalog_items( 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. @@ -717,7 +704,6 @@ async def import_catalog_items( # 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: @@ -736,7 +722,8 @@ async def import_catalog_items( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py index b040285e..e6b18e28 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +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 @@ -39,8 +37,7 @@ 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 as field_mask # type: ignore - +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 @@ -61,7 +58,7 @@ class CatalogServiceClientMeta(type): _transport_registry["grpc_asyncio"] = CatalogServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[CatalogServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -86,7 +83,8 @@ class CatalogServiceClient(metaclass=CatalogServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -120,7 +118,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -137,7 +136,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -156,23 +155,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> CatalogServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - CatalogServiceTransport: The transport used by the client instance. + CatalogServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def catalog_path(project: str, location: str, catalog: str,) -> str: - """Return a fully-qualified catalog string.""" + """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]: - """Parse a catalog path into its component segments.""" + """Parses a catalog path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)$", path, @@ -181,7 +181,7 @@ def parse_catalog_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -194,7 +194,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -205,7 +205,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -216,7 +216,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -227,7 +227,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -241,12 +241,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, CatalogServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the catalog service client. + """Instantiates the catalog service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -301,9 +301,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -315,12 +316,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -335,8 +338,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -369,7 +372,7 @@ def create_catalog_item( CreateCatalogItem method. parent (str): Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog`` + ``projects/*/locations/global/catalogs/default_catalog``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -379,7 +382,6 @@ def create_catalog_item( 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. @@ -408,10 +410,8 @@ def create_catalog_item( # 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: @@ -450,12 +450,11 @@ def get_catalog_item( method. name (str): Required. Full resource name of catalog item, such as - ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_id`` + ``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. @@ -484,10 +483,8 @@ def get_catalog_item( # 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 @@ -525,7 +522,7 @@ def list_catalog_items( method. parent (str): Required. The parent catalog resource name, such as - ``projects/*/locations/global/catalogs/default_catalog`` + ``projects/*/locations/global/catalogs/default_catalog``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -537,7 +534,6 @@ def list_catalog_items( 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. @@ -569,10 +565,8 @@ def list_catalog_items( # 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: @@ -606,7 +600,7 @@ def update_catalog_item( *, name: str = None, catalog_item: catalog.CatalogItem = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -640,7 +634,6 @@ def update_catalog_item( 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. @@ -669,10 +662,8 @@ def update_catalog_item( # 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: @@ -713,12 +704,11 @@ def delete_catalog_item( DeleteCatalogItem method. name (str): Required. Full resource name of catalog item, such as - ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id`` + ``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. @@ -741,10 +731,8 @@ def delete_catalog_item( # 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 @@ -788,7 +776,7 @@ def import_catalog_items( The request object. Request message for Import methods. parent (str): Required. - "projects/1234/locations/global/catalogs/default_catalog" + ``projects/1234/locations/global/catalogs/default_catalog`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -820,7 +808,6 @@ def import_catalog_items( 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. @@ -853,10 +840,8 @@ def import_catalog_items( # 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: diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py index f1242353..d05bd814 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py index dac1279d..fc02f5f3 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py index f52726a5..102016eb 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,24 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # 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 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -42,27 +41,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__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 = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -71,7 +84,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -85,29 +98,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -118,7 +178,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -132,7 +193,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -146,7 +208,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -160,7 +223,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -174,7 +238,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -188,7 +253,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -205,29 +271,29 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def create_catalog_item( self, - ) -> typing.Callable[ + ) -> Callable[ [catalog_service.CreateCatalogItemRequest], - typing.Union[catalog.CatalogItem, typing.Awaitable[catalog.CatalogItem]], + Union[catalog.CatalogItem, Awaitable[catalog.CatalogItem]], ]: raise NotImplementedError() @property def get_catalog_item( self, - ) -> typing.Callable[ + ) -> Callable[ [catalog_service.GetCatalogItemRequest], - typing.Union[catalog.CatalogItem, typing.Awaitable[catalog.CatalogItem]], + Union[catalog.CatalogItem, Awaitable[catalog.CatalogItem]], ]: raise NotImplementedError() @property def list_catalog_items( self, - ) -> typing.Callable[ + ) -> Callable[ [catalog_service.ListCatalogItemsRequest], - typing.Union[ + Union[ catalog_service.ListCatalogItemsResponse, - typing.Awaitable[catalog_service.ListCatalogItemsResponse], + Awaitable[catalog_service.ListCatalogItemsResponse], ], ]: raise NotImplementedError() @@ -235,27 +301,27 @@ def list_catalog_items( @property def update_catalog_item( self, - ) -> typing.Callable[ + ) -> Callable[ [catalog_service.UpdateCatalogItemRequest], - typing.Union[catalog.CatalogItem, typing.Awaitable[catalog.CatalogItem]], + Union[catalog.CatalogItem, Awaitable[catalog.CatalogItem]], ]: raise NotImplementedError() @property def delete_catalog_item( self, - ) -> typing.Callable[ + ) -> Callable[ [catalog_service.DeleteCatalogItemRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def import_catalog_items( self, - ) -> typing.Callable[ + ) -> Callable[ [import_.ImportCatalogItemsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py index 3a25e184..e639fa7e 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +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 @@ -30,9 +28,8 @@ 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 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import CatalogServiceTransport, DEFAULT_CLIENT_INFO @@ -56,7 +53,7 @@ def __init__( self, *, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -70,7 +67,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -181,7 +179,7 @@ def __init__( def create_channel( cls, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,13 +210,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -353,7 +353,7 @@ def update_catalog_item( @property def delete_catalog_item( self, - ) -> Callable[[catalog_service.DeleteCatalogItemRequest], empty.Empty]: + ) -> Callable[[catalog_service.DeleteCatalogItemRequest], empty_pb2.Empty]: r"""Return a callable for the delete catalog item method over gRPC. Deletes a catalog item. @@ -372,14 +372,14 @@ def delete_catalog_item( 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.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_catalog_item"] @property def import_catalog_items( self, - ) -> Callable[[import_.ImportCatalogItemsRequest], operations.Operation]: + ) -> 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 @@ -404,7 +404,7 @@ def import_catalog_items( self._stubs["import_catalog_items"] = self.grpc_channel.unary_unary( "/google.cloud.recommendationengine.v1beta1.CatalogService/ImportCatalogItems", request_serializer=import_.ImportCatalogItemsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_catalog_items"] diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py index f63a2e53..6e4e0971 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,15 @@ # 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -31,9 +29,8 @@ 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 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +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 @@ -59,7 +56,7 @@ class CatalogServiceGrpcAsyncIOTransport(CatalogServiceTransport): def create_channel( cls, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -86,13 +83,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -100,7 +99,7 @@ def __init__( self, *, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -114,7 +113,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -173,7 +173,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -365,7 +364,9 @@ def update_catalog_item( @property def delete_catalog_item( self, - ) -> Callable[[catalog_service.DeleteCatalogItemRequest], Awaitable[empty.Empty]]: + ) -> Callable[ + [catalog_service.DeleteCatalogItemRequest], Awaitable[empty_pb2.Empty] + ]: r"""Return a callable for the delete catalog item method over gRPC. Deletes a catalog item. @@ -384,14 +385,16 @@ def delete_catalog_item( 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.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_catalog_item"] @property def import_catalog_items( self, - ) -> Callable[[import_.ImportCatalogItemsRequest], Awaitable[operations.Operation]]: + ) -> 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 @@ -416,7 +419,7 @@ def import_catalog_items( self._stubs["import_catalog_items"] = self.grpc_channel.unary_unary( "/google.cloud.recommendationengine.v1beta1.CatalogService/ImportCatalogItems", request_serializer=import_.ImportCatalogItemsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_catalog_items"] diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py index 19d1478c..c0a8178d 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import PredictionApiKeyRegistryClient from .async_client import PredictionApiKeyRegistryAsyncClient diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py index b3c3251d..f955d504 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import ( @@ -34,7 +32,6 @@ 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 @@ -64,33 +61,28 @@ class PredictionApiKeyRegistryAsyncClient: 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 ) @@ -100,7 +92,8 @@ class PredictionApiKeyRegistryAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -115,7 +108,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -132,7 +125,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> PredictionApiKeyRegistryTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: PredictionApiKeyRegistryTransport: The transport used by the client instance. @@ -147,12 +140,12 @@ def transport(self) -> PredictionApiKeyRegistryTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, PredictionApiKeyRegistryTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the prediction api key registry client. + """Instantiates the prediction api key registry client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -184,7 +177,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = PredictionApiKeyRegistryClient( credentials=credentials, transport=transport, @@ -210,7 +202,7 @@ async def create_prediction_api_key_registration( `CreatePredictionApiKeyRegistration` method. parent (:class:`str`): Required. The parent resource path. - ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + ``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 @@ -222,7 +214,6 @@ async def create_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. @@ -249,7 +240,6 @@ async def create_prediction_api_key_registration( # 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: @@ -264,7 +254,8 @@ async def create_prediction_api_key_registration( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -302,12 +293,11 @@ async def list_prediction_api_key_registrations( `ListPredictionApiKeyRegistrations`. parent (:class:`str`): Required. The parent placement resource name such as - "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store" + ``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. @@ -339,7 +329,6 @@ async def list_prediction_api_key_registrations( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -352,7 +341,8 @@ async def list_prediction_api_key_registrations( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -401,7 +391,6 @@ async def delete_prediction_api_key_registration( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -424,7 +413,6 @@ async def delete_prediction_api_key_registration( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -437,7 +425,8 @@ async def delete_prediction_api_key_registration( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py index 8a2f5c5a..0848b4c1 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +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 @@ -38,7 +36,6 @@ 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 @@ -61,7 +58,7 @@ class PredictionApiKeyRegistryClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[PredictionApiKeyRegistryTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -90,7 +87,8 @@ class PredictionApiKeyRegistryClient(metaclass=PredictionApiKeyRegistryClientMet @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -124,7 +122,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -141,7 +140,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -160,10 +159,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> PredictionApiKeyRegistryTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - PredictionApiKeyRegistryTransport: The transport used by the client instance. + PredictionApiKeyRegistryTransport: The transport used by the client + instance. """ return self._transport @@ -171,7 +171,7 @@ def transport(self) -> PredictionApiKeyRegistryTransport: def event_store_path( project: str, location: str, catalog: str, event_store: str, ) -> str: - """Return a fully-qualified event_store string.""" + """Returns a fully-qualified event_store string.""" return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format( project=project, location=location, @@ -181,7 +181,7 @@ def event_store_path( @staticmethod def parse_event_store_path(path: str) -> Dict[str, str]: - """Parse a event_store path into its component segments.""" + """Parses a event_store path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)$", path, @@ -196,7 +196,7 @@ def prediction_api_key_registration_path( event_store: str, prediction_api_key_registration: str, ) -> str: - """Return a fully-qualified prediction_api_key_registration string.""" + """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, @@ -207,7 +207,7 @@ def prediction_api_key_registration_path( @staticmethod def parse_prediction_api_key_registration_path(path: str) -> Dict[str, str]: - """Parse a prediction_api_key_registration path into its component segments.""" + """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, @@ -216,7 +216,7 @@ def parse_prediction_api_key_registration_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -229,7 +229,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -240,7 +240,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -251,7 +251,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -262,7 +262,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -276,12 +276,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, PredictionApiKeyRegistryTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the prediction api key registry client. + """Instantiates the prediction api key registry client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -336,9 +336,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -350,12 +351,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -370,8 +373,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -404,7 +407,7 @@ def create_prediction_api_key_registration( `CreatePredictionApiKeyRegistration` method. parent (str): Required. The parent resource path. - ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + ``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 @@ -416,7 +419,6 @@ def create_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. @@ -448,10 +450,8 @@ def create_prediction_api_key_registration( 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: @@ -495,12 +495,11 @@ def list_prediction_api_key_registrations( `ListPredictionApiKeyRegistrations`. parent (str): Required. The parent placement resource name such as - "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store" + ``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. @@ -537,10 +536,8 @@ def list_prediction_api_key_registrations( 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 @@ -591,7 +588,6 @@ def delete_prediction_api_key_registration( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -619,10 +615,8 @@ def delete_prediction_api_key_registration( 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 diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py index 1f565842..75bb5226 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -135,7 +133,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py index 75ef7aa6..5f9a2a13 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py index 891c14b7..605f3dcb 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.recommendationengine_v1beta1.types import ( prediction_apikey_registry_service, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -40,27 +39,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__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 = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -69,7 +82,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -83,29 +96,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,7 +176,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -130,7 +191,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -144,7 +206,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -156,13 +219,11 @@ def _prep_wrapped_messages(self, client_info): @property def create_prediction_api_key_registration( self, - ) -> typing.Callable[ + ) -> Callable[ [prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest], - typing.Union[ + Union[ prediction_apikey_registry_service.PredictionApiKeyRegistration, - typing.Awaitable[ - prediction_apikey_registry_service.PredictionApiKeyRegistration - ], + Awaitable[prediction_apikey_registry_service.PredictionApiKeyRegistration], ], ]: raise NotImplementedError() @@ -170,11 +231,11 @@ def create_prediction_api_key_registration( @property def list_prediction_api_key_registrations( self, - ) -> typing.Callable[ + ) -> Callable[ [prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest], - typing.Union[ + Union[ prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse, - typing.Awaitable[ + Awaitable[ prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse ], ], @@ -184,9 +245,9 @@ def list_prediction_api_key_registrations( @property def delete_prediction_api_key_registration( self, - ) -> typing.Callable[ + ) -> Callable[ [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py index 8e7918cb..6e7033a1 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +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 @@ -29,8 +27,7 @@ from google.cloud.recommendationengine_v1beta1.types import ( prediction_apikey_registry_service, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO @@ -58,7 +55,7 @@ def __init__( self, *, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -72,7 +69,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -182,7 +180,7 @@ def __init__( def create_channel( cls, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -213,13 +211,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -299,7 +299,7 @@ def delete_prediction_api_key_registration( self, ) -> Callable[ [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], - empty.Empty, + empty_pb2.Empty, ]: r"""Return a callable for the delete prediction api key registration method over gRPC. @@ -322,7 +322,7 @@ def 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.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_prediction_api_key_registration"] diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py index 8ecd591b..10286275 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_api_key_registry/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -30,8 +28,7 @@ from google.cloud.recommendationengine_v1beta1.types import ( prediction_apikey_registry_service, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import PredictionApiKeyRegistryTransport, DEFAULT_CLIENT_INFO from .grpc import PredictionApiKeyRegistryGrpcTransport @@ -61,7 +58,7 @@ class PredictionApiKeyRegistryGrpcAsyncIOTransport(PredictionApiKeyRegistryTrans def create_channel( cls, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -88,13 +85,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -102,7 +101,7 @@ def __init__( self, *, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -116,7 +115,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -174,7 +174,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -305,7 +304,7 @@ def delete_prediction_api_key_registration( self, ) -> Callable[ [prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest], - Awaitable[empty.Empty], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the delete prediction api key registration method over gRPC. @@ -328,7 +327,7 @@ def 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.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_prediction_api_key_registration"] diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py index 0c847693..12491bb1 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import PredictionServiceClient from .async_client import PredictionServiceAsyncClient diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py index f00d87e4..25ad2792 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,16 +20,15 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # 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 @@ -47,31 +44,26 @@ class PredictionServiceAsyncClient: 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 @@ -79,7 +71,8 @@ class PredictionServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -94,7 +87,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -111,7 +104,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> PredictionServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: PredictionServiceTransport: The transport used by the client instance. @@ -125,12 +118,12 @@ def transport(self) -> PredictionServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, PredictionServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the prediction service client. + """Instantiates the prediction service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -162,7 +155,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = PredictionServiceClient( credentials=credentials, transport=transport, @@ -191,7 +183,7 @@ async def predict( 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/*} + ``{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. @@ -243,7 +235,6 @@ async def predict( 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. @@ -272,7 +263,6 @@ async def predict( # 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: @@ -287,7 +277,8 @@ async def predict( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py index 75617c51..9c61ea2f 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +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 @@ -35,7 +33,6 @@ 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 @@ -58,7 +55,7 @@ class PredictionServiceClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[PredictionServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -81,7 +78,8 @@ class PredictionServiceClient(metaclass=PredictionServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -115,7 +113,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -132,7 +131,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -151,10 +150,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> PredictionServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - PredictionServiceTransport: The transport used by the client instance. + PredictionServiceTransport: The transport used by the client + instance. """ return self._transport @@ -162,7 +162,7 @@ def transport(self) -> PredictionServiceTransport: def placement_path( project: str, location: str, catalog: str, event_store: str, placement: str, ) -> str: - """Return a fully-qualified placement string.""" + """Returns a fully-qualified placement string.""" return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/placements/{placement}".format( project=project, location=location, @@ -173,7 +173,7 @@ def placement_path( @staticmethod def parse_placement_path(path: str) -> Dict[str, str]: - """Parse a placement path into its component segments.""" + """Parses a placement path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)/placements/(?P.+?)$", path, @@ -182,7 +182,7 @@ def parse_placement_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -195,7 +195,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -206,7 +206,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -217,7 +217,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -228,7 +228,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -242,12 +242,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, PredictionServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the prediction service client. + """Instantiates the prediction service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -302,9 +302,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -316,12 +317,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -336,8 +339,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -373,7 +376,7 @@ def predict( 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/*} + ``{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. @@ -425,7 +428,6 @@ def predict( 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. @@ -456,10 +458,8 @@ def predict( # 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: diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py index 05d9251e..a5af841e 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py index 9ec1369a..86d2e8a7 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py index 9b3d901a..c84024c9 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.recommendationengine_v1beta1.types import prediction_service - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -37,27 +36,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__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 = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -66,7 +79,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -80,29 +93,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -113,7 +173,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -125,11 +186,11 @@ def _prep_wrapped_messages(self, client_info): @property def predict( self, - ) -> typing.Callable[ + ) -> Callable[ [prediction_service.PredictRequest], - typing.Union[ + Union[ prediction_service.PredictResponse, - typing.Awaitable[prediction_service.PredictResponse], + Awaitable[prediction_service.PredictResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py index 0c18a57c..2c29280c 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +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 @@ -50,7 +47,7 @@ def __init__( self, *, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -64,7 +61,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -174,7 +172,7 @@ def __init__( def create_channel( cls, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -205,13 +203,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py index 56dd10e7..a87304b1 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version 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 @@ -53,7 +50,7 @@ class PredictionServiceGrpcAsyncIOTransport(PredictionServiceTransport): def create_channel( cls, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -80,13 +77,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -94,7 +93,7 @@ def __init__( self, *, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -108,7 +107,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -166,7 +166,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py b/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py index 33435f73..5d067fc3 100644 --- a/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/user_event_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import UserEventServiceClient from .async_client import UserEventServiceAsyncClient diff --git a/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py b/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py index fe2b306c..bbb39b17 100644 --- a/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py +++ b/google/cloud/recommendationengine_v1beta1/services/user_event_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,13 +20,13 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -from google.api import httpbody_pb2 as httpbody # 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 @@ -36,9 +34,8 @@ 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 as gp_any # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport from .client import UserEventServiceClient @@ -56,31 +53,26 @@ class UserEventServiceAsyncClient: 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 @@ -88,7 +80,8 @@ class UserEventServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -103,7 +96,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -120,7 +113,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> UserEventServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: UserEventServiceTransport: The transport used by the client instance. @@ -134,12 +127,12 @@ def transport(self) -> UserEventServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the user event service client. + """Instantiates the user event service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -171,7 +164,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = UserEventServiceClient( credentials=credentials, transport=transport, @@ -197,7 +189,7 @@ async def write_user_event( method. parent (:class:`str`): Required. The parent eventStore resource name, such as - "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store". + ``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 @@ -207,7 +199,6 @@ async def write_user_event( 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. @@ -236,7 +227,6 @@ async def write_user_event( # 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: @@ -251,7 +241,8 @@ async def write_user_event( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -282,7 +273,7 @@ async def collect_user_event( retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody.HttpBody: + ) -> 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. @@ -296,7 +287,7 @@ async def collect_user_event( method. parent (:class:`str`): Required. The parent eventStore name, such as - "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store". + ``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 @@ -331,7 +322,6 @@ async def collect_user_event( 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. @@ -401,7 +391,6 @@ async def collect_user_event( # 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: @@ -420,7 +409,8 @@ async def collect_user_event( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -459,7 +449,7 @@ async def list_user_events( method. parent (:class:`str`): Required. The parent eventStore resource name, such as - ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store`` + ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -505,7 +495,6 @@ async def list_user_events( 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. @@ -535,7 +524,6 @@ async def list_user_events( # 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: @@ -550,7 +538,8 @@ async def list_user_events( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -600,7 +589,7 @@ async def purge_user_events( 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}" + ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -639,7 +628,6 @@ async def purge_user_events( 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. @@ -669,7 +657,6 @@ async def purge_user_events( # 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: @@ -686,7 +673,8 @@ async def purge_user_events( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -740,7 +728,7 @@ async def import_user_events( ImportUserEvents request. parent (:class:`str`): Required. - "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store" + ``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 @@ -771,7 +759,6 @@ async def import_user_events( 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. @@ -803,7 +790,6 @@ async def import_user_events( # 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: @@ -822,7 +808,8 @@ async def import_user_events( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py b/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py index c00bcae6..cd120ba5 100644 --- a/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py +++ b/google/cloud/recommendationengine_v1beta1/services/user_event_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,16 +21,16 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore -from google.api import httpbody_pb2 as httpbody # 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 @@ -40,9 +38,8 @@ 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 as gp_any # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import UserEventServiceGrpcTransport from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport @@ -63,7 +60,7 @@ class UserEventServiceClientMeta(type): _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[UserEventServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -88,7 +85,8 @@ class UserEventServiceClient(metaclass=UserEventServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -122,7 +120,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -139,7 +138,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -158,10 +157,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> UserEventServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - UserEventServiceTransport: The transport used by the client instance. + UserEventServiceTransport: The transport used by the client + instance. """ return self._transport @@ -169,7 +169,7 @@ def transport(self) -> UserEventServiceTransport: def event_store_path( project: str, location: str, catalog: str, event_store: str, ) -> str: - """Return a fully-qualified event_store string.""" + """Returns a fully-qualified event_store string.""" return "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}".format( project=project, location=location, @@ -179,7 +179,7 @@ def event_store_path( @staticmethod def parse_event_store_path(path: str) -> Dict[str, str]: - """Parse a event_store path into its component segments.""" + """Parses a event_store path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/catalogs/(?P.+?)/eventStores/(?P.+?)$", path, @@ -188,7 +188,7 @@ def parse_event_store_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -201,7 +201,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -212,7 +212,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -223,7 +223,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -234,7 +234,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -248,12 +248,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, UserEventServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the user event service client. + """Instantiates the user event service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -308,9 +308,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -322,12 +323,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -342,8 +345,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -376,7 +379,7 @@ def write_user_event( method. parent (str): Required. The parent eventStore resource name, such as - "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store". + ``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 @@ -386,7 +389,6 @@ def write_user_event( 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. @@ -417,10 +419,8 @@ def write_user_event( # 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: @@ -453,7 +453,7 @@ def collect_user_event( retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody.HttpBody: + ) -> 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. @@ -467,7 +467,7 @@ def collect_user_event( method. parent (str): Required. The parent eventStore name, such as - "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store". + ``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 @@ -502,7 +502,6 @@ def collect_user_event( 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. @@ -574,10 +573,8 @@ def collect_user_event( # 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: @@ -622,7 +619,7 @@ def list_user_events( method. parent (str): Required. The parent eventStore resource name, such as - ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store`` + ``projects/*/locations/*/catalogs/default_catalog/eventStores/default_event_store``. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -668,7 +665,6 @@ def list_user_events( 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. @@ -700,10 +696,8 @@ def list_user_events( # 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: @@ -755,7 +749,7 @@ def purge_user_events( 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}" + ``projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -794,7 +788,6 @@ def purge_user_events( 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. @@ -826,10 +819,8 @@ def purge_user_events( # 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: @@ -887,7 +878,7 @@ def import_user_events( ImportUserEvents request. parent (str): Required. - "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store" + ``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 @@ -918,7 +909,6 @@ def import_user_events( 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. @@ -952,10 +942,8 @@ def import_user_events( # 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: diff --git a/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py b/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py index 1e81f9d7..1b373fcc 100644 --- a/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py +++ b/google/cloud/recommendationengine_v1beta1/services/user_event_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py index c9246aa4..4c90ca7e 100644 --- a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py index 3db40469..49e1a2d7 100644 --- a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py +++ b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,24 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore -from google.api import httpbody_pb2 as httpbody # 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 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -42,27 +41,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__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 = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -71,7 +84,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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): @@ -85,29 +98,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -118,7 +178,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -132,7 +193,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -146,7 +208,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -160,7 +223,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -174,7 +238,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -191,31 +256,29 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def write_user_event( self, - ) -> typing.Callable[ + ) -> Callable[ [user_event_service.WriteUserEventRequest], - typing.Union[ - gcr_user_event.UserEvent, typing.Awaitable[gcr_user_event.UserEvent] - ], + Union[gcr_user_event.UserEvent, Awaitable[gcr_user_event.UserEvent]], ]: raise NotImplementedError() @property def collect_user_event( self, - ) -> typing.Callable[ + ) -> Callable[ [user_event_service.CollectUserEventRequest], - typing.Union[httpbody.HttpBody, typing.Awaitable[httpbody.HttpBody]], + Union[httpbody_pb2.HttpBody, Awaitable[httpbody_pb2.HttpBody]], ]: raise NotImplementedError() @property def list_user_events( self, - ) -> typing.Callable[ + ) -> Callable[ [user_event_service.ListUserEventsRequest], - typing.Union[ + Union[ user_event_service.ListUserEventsResponse, - typing.Awaitable[user_event_service.ListUserEventsResponse], + Awaitable[user_event_service.ListUserEventsResponse], ], ]: raise NotImplementedError() @@ -223,18 +286,18 @@ def list_user_events( @property def purge_user_events( self, - ) -> typing.Callable[ + ) -> Callable[ [user_event_service.PurgeUserEventsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def import_user_events( self, - ) -> typing.Callable[ + ) -> Callable[ [import_.ImportUserEventsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py index fbfe1a2c..765a27f6 100644 --- a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py +++ b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +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 as httpbody # 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 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO @@ -56,7 +53,7 @@ def __init__( self, *, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -70,7 +67,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -181,7 +179,7 @@ def __init__( def create_channel( cls, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,13 +210,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -271,7 +271,7 @@ def write_user_event( @property def collect_user_event( self, - ) -> Callable[[user_event_service.CollectUserEventRequest], httpbody.HttpBody]: + ) -> 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 @@ -295,7 +295,7 @@ def collect_user_event( 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.HttpBody.FromString, + response_deserializer=httpbody_pb2.HttpBody.FromString, ) return self._stubs["collect_user_event"] @@ -332,7 +332,9 @@ def list_user_events( @property def purge_user_events( self, - ) -> Callable[[user_event_service.PurgeUserEventsRequest], operations.Operation]: + ) -> 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 @@ -355,14 +357,14 @@ def purge_user_events( 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.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["purge_user_events"] @property def import_user_events( self, - ) -> Callable[[import_.ImportUserEventsRequest], operations.Operation]: + ) -> 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 @@ -387,7 +389,7 @@ def import_user_events( self._stubs["import_user_events"] = self.grpc_channel.unary_unary( "/google.cloud.recommendationengine.v1beta1.UserEventService/ImportUserEvents", request_serializer=import_.ImportUserEventsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_user_events"] diff --git a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py index af3fb16c..0c7c5a06 100644 --- a/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py +++ b/google/cloud/recommendationengine_v1beta1/services/user_event_service/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,26 +13,24 @@ # 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore -from google.api import httpbody_pb2 as httpbody # 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 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO from .grpc import UserEventServiceGrpcTransport @@ -59,7 +56,7 @@ class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): def create_channel( cls, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -86,13 +83,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -100,7 +99,7 @@ def __init__( self, *, host: str = "recommendationengine.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -114,7 +113,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -173,7 +173,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -280,7 +279,7 @@ def write_user_event( def collect_user_event( self, ) -> Callable[ - [user_event_service.CollectUserEventRequest], Awaitable[httpbody.HttpBody] + [user_event_service.CollectUserEventRequest], Awaitable[httpbody_pb2.HttpBody] ]: r"""Return a callable for the collect user event method over gRPC. @@ -305,7 +304,7 @@ def collect_user_event( 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.HttpBody.FromString, + response_deserializer=httpbody_pb2.HttpBody.FromString, ) return self._stubs["collect_user_event"] @@ -343,7 +342,7 @@ def list_user_events( def purge_user_events( self, ) -> Callable[ - [user_event_service.PurgeUserEventsRequest], Awaitable[operations.Operation] + [user_event_service.PurgeUserEventsRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the purge user events method over gRPC. @@ -367,14 +366,16 @@ def purge_user_events( 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.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["purge_user_events"] @property def import_user_events( self, - ) -> Callable[[import_.ImportUserEventsRequest], Awaitable[operations.Operation]]: + ) -> 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 @@ -399,7 +400,7 @@ def import_user_events( self._stubs["import_user_events"] = self.grpc_channel.unary_unary( "/google.cloud.recommendationengine.v1beta1.UserEventService/ImportUserEvents", request_serializer=import_.ImportUserEventsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_user_events"] diff --git a/google/cloud/recommendationengine_v1beta1/types/__init__.py b/google/cloud/recommendationengine_v1beta1/types/__init__.py index fc832b8c..895d1c28 100644 --- a/google/cloud/recommendationengine_v1beta1/types/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .catalog import ( CatalogItem, Image, diff --git a/google/cloud/recommendationengine_v1beta1/types/catalog.py b/google/cloud/recommendationengine_v1beta1/types/catalog.py index ab92b2af..31813d64 100644 --- a/google/cloud/recommendationengine_v1beta1/types/catalog.py +++ b/google/cloud/recommendationengine_v1beta1/types/catalog.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.recommendationengine_v1beta1.types import common @@ -95,7 +92,6 @@ class CatalogItem(proto.Message): class CategoryHierarchy(proto.Message): r"""Category represents catalog item category hierarchy. - Attributes: categories (Sequence[str]): Required. Catalog item categories. Each @@ -105,26 +101,18 @@ class CategoryHierarchy(proto.Message): specificity (from least to most specific). """ - categories = proto.RepeatedField(proto.STRING, number=1) - - id = proto.Field(proto.STRING, number=1) + categories = proto.RepeatedField(proto.STRING, number=1,) + id = proto.Field(proto.STRING, number=1,) category_hierarchies = proto.RepeatedField( proto.MESSAGE, number=2, message=CategoryHierarchy, ) - - title = proto.Field(proto.STRING, number=3) - - description = proto.Field(proto.STRING, number=4) - + title = proto.Field(proto.STRING, number=3,) + description = proto.Field(proto.STRING, number=4,) item_attributes = proto.Field(proto.MESSAGE, number=5, message=common.FeatureMap,) - - language_code = proto.Field(proto.STRING, number=6) - - tags = proto.RepeatedField(proto.STRING, number=8) - - item_group_id = proto.Field(proto.STRING, number=9) - + language_code = proto.Field(proto.STRING, number=6,) + tags = proto.RepeatedField(proto.STRING, number=8,) + item_group_id = proto.Field(proto.STRING, number=9,) product_metadata = proto.Field( proto.MESSAGE, number=10, @@ -184,7 +172,6 @@ class StockState(proto.Enum): class ExactPrice(proto.Message): r"""Exact product price. - Attributes: display_price (float): Optional. Display price of the product. @@ -194,9 +181,8 @@ class ExactPrice(proto.Message): 'displayPrice'. """ - display_price = proto.Field(proto.FLOAT, number=1) - - original_price = proto.Field(proto.FLOAT, number=2) + display_price = proto.Field(proto.FLOAT, number=1,) + original_price = proto.Field(proto.FLOAT, number=2,) class PriceRange(proto.Message): r"""Product price range when there are a range of prices for @@ -209,34 +195,25 @@ class PriceRange(proto.Message): Required. The maximum product price. """ - min_ = proto.Field(proto.FLOAT, number=1) - - max_ = proto.Field(proto.FLOAT, number=2) + min_ = proto.Field(proto.FLOAT, number=1,) + max_ = proto.Field(proto.FLOAT, number=2,) exact_price = proto.Field( proto.MESSAGE, number=1, oneof="price", message=ExactPrice, ) - price_range = proto.Field( proto.MESSAGE, number=2, oneof="price", message=PriceRange, ) - - costs = proto.MapField(proto.STRING, proto.FLOAT, number=3) - - currency_code = proto.Field(proto.STRING, number=4) - + costs = proto.MapField(proto.STRING, proto.FLOAT, number=3,) + currency_code = proto.Field(proto.STRING, number=4,) stock_state = proto.Field(proto.ENUM, number=5, enum=StockState,) - - available_quantity = proto.Field(proto.INT64, number=6) - - canonical_product_uri = proto.Field(proto.STRING, number=7) - + available_quantity = proto.Field(proto.INT64, number=6,) + canonical_product_uri = proto.Field(proto.STRING, number=7,) images = 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 @@ -249,11 +226,9 @@ class Image(proto.Message): pixels. """ - uri = proto.Field(proto.STRING, number=1) - - height = proto.Field(proto.INT32, number=2) - - width = proto.Field(proto.INT32, number=3) + uri = proto.Field(proto.STRING, number=1,) + height = proto.Field(proto.INT32, number=2,) + width = proto.Field(proto.INT32, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/recommendationengine_v1beta1/types/catalog_service.py b/google/cloud/recommendationengine_v1beta1/types/catalog_service.py index bb04239c..86da784d 100644 --- a/google/cloud/recommendationengine_v1beta1/types/catalog_service.py +++ b/google/cloud/recommendationengine_v1beta1/types/catalog_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.recommendationengine_v1beta1.types import catalog -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -37,39 +34,35 @@ 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`` + ``projects/*/locations/global/catalogs/default_catalog``. catalog_item (google.cloud.recommendationengine_v1beta1.types.CatalogItem): Required. The catalog item to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) catalog_item = 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`` + ``projects/*/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_id``. """ - name = proto.Field(proto.STRING, number=1) + name = 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`` + ``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 @@ -82,18 +75,14 @@ class ListCatalogItemsRequest(proto.Message): results. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListCatalogItemsResponse(proto.Message): r"""Response message for ListCatalogItems method. - Attributes: catalog_items (Sequence[google.cloud.recommendationengine_v1beta1.types.CatalogItem]): The catalog items. @@ -110,13 +99,11 @@ def raw_page(self): catalog_items = proto.RepeatedField( proto.MESSAGE, number=1, message=catalog.CatalogItem, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = 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 @@ -130,23 +117,22 @@ class UpdateCatalogItemRequest(proto.Message): default update all fields. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) catalog_item = proto.Field(proto.MESSAGE, number=2, message=catalog.CatalogItem,) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + update_mask = 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`` + ``projects/*/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/recommendationengine_v1beta1/types/common.py b/google/cloud/recommendationengine_v1beta1/types/common.py index 8d79cc1a..fa8964d8 100644 --- a/google/cloud/recommendationengine_v1beta1/types/common.py +++ b/google/cloud/recommendationengine_v1beta1/types/common.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -50,29 +48,26 @@ class FeatureMap(proto.Message): class StringList(proto.Message): r"""A list of string features. - Attributes: value (Sequence[str]): String feature value with a length limit of 128 bytes. """ - value = proto.RepeatedField(proto.STRING, number=1) + value = proto.RepeatedField(proto.STRING, number=1,) class FloatList(proto.Message): r"""A list of float features. - Attributes: value (Sequence[float]): Float feature value. """ - value = proto.RepeatedField(proto.FLOAT, number=1) + value = proto.RepeatedField(proto.FLOAT, number=1,) categorical_features = proto.MapField( proto.STRING, proto.MESSAGE, number=1, message=StringList, ) - numerical_features = proto.MapField( proto.STRING, proto.MESSAGE, number=2, message=FloatList, ) diff --git a/google/cloud/recommendationengine_v1beta1/types/import_.py b/google/cloud/recommendationengine_v1beta1/types/import_.py index 10b70713..bb19a7bd 100644 --- a/google/cloud/recommendationengine_v1beta1/types/import_.py +++ b/google/cloud/recommendationengine_v1beta1/types/import_.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - 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 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -50,16 +47,16 @@ class GcsSource(proto.Message): input_uris (Sequence[str]): Required. Google Cloud Storage URIs to input files. URI can be up to 2000 characters long. URIs can match the full - object path (for example, gs://bucket/directory/object.json) - or a pattern matching one or more files, such as - ``gs://bucket/directory/*.json``. A request can contain at most - 100 files, and each file can be up to 2 GB. See `Importing - catalog + 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 = proto.RepeatedField(proto.STRING, number=1) + input_uris = proto.RepeatedField(proto.STRING, number=1,) class CatalogInlineSource(proto.Message): @@ -94,7 +91,6 @@ class UserEventInlineSource(proto.Message): class ImportErrorsConfig(proto.Message): r"""Configuration of destination for Import related errors. - Attributes: gcs_prefix (str): Google Cloud Storage path for import errors. This must be an @@ -103,16 +99,15 @@ class ImportErrorsConfig(proto.Message): JSON-encoded ``google.rpc.Status`` message. """ - gcs_prefix = proto.Field(proto.STRING, number=1, oneof="destination") + gcs_prefix = 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". + ``projects/1234/locations/global/catalogs/default_catalog`` request_id (str): Optional. Unique identifier provided by client, within the ancestor dataset scope. @@ -129,22 +124,18 @@ class ImportCatalogItemsRequest(proto.Message): incurred during the Import. """ - parent = proto.Field(proto.STRING, number=1) - - request_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + request_id = proto.Field(proto.STRING, number=2,) input_config = proto.Field(proto.MESSAGE, number=3, message="InputConfig",) - errors_config = 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". + ``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 @@ -161,18 +152,14 @@ class ImportUserEventsRequest(proto.Message): incurred during the Import. """ - parent = proto.Field(proto.STRING, number=1) - - request_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + request_id = proto.Field(proto.STRING, number=2,) input_config = proto.Field(proto.MESSAGE, number=3, message="InputConfig",) - errors_config = proto.Field(proto.MESSAGE, number=4, message="ImportErrorsConfig",) class InputConfig(proto.Message): r"""The input config source. - Attributes: catalog_inline_source (google.cloud.recommendationengine_v1beta1.types.CatalogInlineSource): The Inline source for the input content for @@ -188,11 +175,9 @@ class InputConfig(proto.Message): catalog_inline_source = proto.Field( proto.MESSAGE, number=1, oneof="source", message="CatalogInlineSource", ) - gcs_source = proto.Field( proto.MESSAGE, number=2, oneof="source", message="GcsSource", ) - user_event_inline_source = proto.Field( proto.MESSAGE, number=3, oneof="source", message="UserEventInlineSource", ) @@ -223,17 +208,12 @@ class ImportMetadata(proto.Message): is done, this is also the finish time. """ - operation_name = proto.Field(proto.STRING, number=5) - - request_id = proto.Field(proto.STRING, number=3) - - create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - success_count = proto.Field(proto.INT64, number=1) - - failure_count = proto.Field(proto.INT64, number=2) - - update_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + operation_name = proto.Field(proto.STRING, number=5,) + request_id = proto.Field(proto.STRING, number=3,) + create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + success_count = proto.Field(proto.INT64, number=1,) + failure_count = proto.Field(proto.INT64, number=2,) + update_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) class ImportCatalogItemsResponse(proto.Message): @@ -251,8 +231,9 @@ class ImportCatalogItemsResponse(proto.Message): errors in the request if set. """ - error_samples = proto.RepeatedField(proto.MESSAGE, number=1, message=status.Status,) - + error_samples = proto.RepeatedField( + proto.MESSAGE, number=1, message=status_pb2.Status, + ) errors_config = proto.Field(proto.MESSAGE, number=2, message="ImportErrorsConfig",) @@ -274,10 +255,10 @@ class ImportUserEventsResponse(proto.Message): status. """ - error_samples = proto.RepeatedField(proto.MESSAGE, number=1, message=status.Status,) - + error_samples = proto.RepeatedField( + proto.MESSAGE, number=1, message=status_pb2.Status, + ) errors_config = proto.Field(proto.MESSAGE, number=2, message="ImportErrorsConfig",) - import_summary = proto.Field( proto.MESSAGE, number=3, message="UserEventImportSummary", ) @@ -297,9 +278,8 @@ class UserEventImportSummary(proto.Message): catalog. """ - joined_events_count = proto.Field(proto.INT64, number=1) - - unjoined_events_count = proto.Field(proto.INT64, number=2) + joined_events_count = proto.Field(proto.INT64, number=1,) + unjoined_events_count = proto.Field(proto.INT64, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py b/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py index 150f27e8..94dc44fa 100644 --- a/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py +++ b/google/cloud/recommendationengine_v1beta1/types/prediction_apikey_registry_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -32,13 +30,12 @@ class PredictionApiKeyRegistration(proto.Message): r"""Registered Api Key. - Attributes: api_key (str): The API key. """ - api_key = proto.Field(proto.STRING, number=1) + api_key = proto.Field(proto.STRING, number=1,) class CreatePredictionApiKeyRegistrationRequest(proto.Message): @@ -48,14 +45,13 @@ class CreatePredictionApiKeyRegistrationRequest(proto.Message): Attributes: parent (str): Required. The parent resource path. - ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`` + ``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 = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) prediction_api_key_registration = proto.Field( proto.MESSAGE, number=2, message="PredictionApiKeyRegistration", ) @@ -63,11 +59,10 @@ class CreatePredictionApiKeyRegistrationRequest(proto.Message): 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". + ``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 @@ -77,16 +72,13 @@ class ListPredictionApiKeyRegistrationsRequest(proto.Message): ``ListPredictionApiKeyRegistration.nextPageToken``. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListPredictionApiKeyRegistrationsResponse(proto.Message): r"""Response message for the ``ListPredictionApiKeyRegistrations``. - Attributes: prediction_api_key_registrations (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictionApiKeyRegistration]): The list of registered API keys. @@ -103,13 +95,11 @@ def raw_page(self): prediction_api_key_registrations = proto.RepeatedField( proto.MESSAGE, number=1, message="PredictionApiKeyRegistration", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = 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 @@ -117,7 +107,7 @@ class DeletePredictionApiKeyRegistrationRequest(proto.Message): ``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/recommendationengine_v1beta1/types/prediction_service.py b/google/cloud/recommendationengine_v1beta1/types/prediction_service.py index eba37139..2402b138 100644 --- a/google/cloud/recommendationengine_v1beta1/types/prediction_service.py +++ b/google/cloud/recommendationengine_v1beta1/types/prediction_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -30,11 +27,10 @@ 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/*} + ``{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. @@ -141,28 +137,20 @@ class PredictRequest(proto.Message): examples of labels. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) user_event = proto.Field(proto.MESSAGE, number=2, message=gcr_user_event.UserEvent,) - - page_size = proto.Field(proto.INT32, number=7) - - page_token = proto.Field(proto.STRING, number=8) - - filter = proto.Field(proto.STRING, number=3) - - dry_run = proto.Field(proto.BOOL, number=4) - + page_size = proto.Field(proto.INT32, number=7,) + page_token = proto.Field(proto.STRING, number=8,) + filter = proto.Field(proto.STRING, number=3,) + dry_run = proto.Field(proto.BOOL, number=4,) params = proto.MapField( - proto.STRING, proto.MESSAGE, number=6, message=struct.Value, + proto.STRING, proto.MESSAGE, number=6, message=struct_pb2.Value, ) - - labels = proto.MapField(proto.STRING, proto.STRING, number=9) + labels = proto.MapField(proto.STRING, proto.STRING, number=9,) class PredictResponse(proto.Message): r"""Response message for predict method. - Attributes: results (Sequence[google.cloud.recommendationengine_v1beta1.types.PredictResponse.PredictionResult]): A list of recommended items. The order @@ -207,10 +195,9 @@ class PredictionResult(proto.Message): ``PredictRequest.params``. """ - id = proto.Field(proto.STRING, number=1) - + id = proto.Field(proto.STRING, number=1,) item_metadata = proto.MapField( - proto.STRING, proto.MESSAGE, number=2, message=struct.Value, + proto.STRING, proto.MESSAGE, number=2, message=struct_pb2.Value, ) @property @@ -218,18 +205,13 @@ def raw_page(self): return self results = proto.RepeatedField(proto.MESSAGE, number=1, message=PredictionResult,) - - recommendation_token = proto.Field(proto.STRING, number=2) - - items_missing_in_catalog = proto.RepeatedField(proto.STRING, number=3) - - dry_run = proto.Field(proto.BOOL, number=4) - + recommendation_token = proto.Field(proto.STRING, number=2,) + items_missing_in_catalog = proto.RepeatedField(proto.STRING, number=3,) + dry_run = proto.Field(proto.BOOL, number=4,) metadata = proto.MapField( - proto.STRING, proto.MESSAGE, number=5, message=struct.Value, + proto.STRING, proto.MESSAGE, number=5, message=struct_pb2.Value, ) - - next_page_token = proto.Field(proto.STRING, number=6) + next_page_token = proto.Field(proto.STRING, number=6,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py b/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py index b9777025..29a95c74 100644 --- a/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py +++ b/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/recommendationengine_v1beta1/types/user_event.py b/google/cloud/recommendationengine_v1beta1/types/user_event.py index 8c1f0e3a..164c3061 100644 --- a/google/cloud/recommendationengine_v1beta1/types/user_event.py +++ b/google/cloud/recommendationengine_v1beta1/types/user_event.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - 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 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -110,24 +107,18 @@ class EventSource(proto.Enum): ECOMMERCE = 2 BATCH_UPLOAD = 3 - event_type = proto.Field(proto.STRING, number=1) - + event_type = proto.Field(proto.STRING, number=1,) user_info = proto.Field(proto.MESSAGE, number=2, message="UserInfo",) - event_detail = proto.Field(proto.MESSAGE, number=3, message="EventDetail",) - product_event_detail = proto.Field( proto.MESSAGE, number=4, message="ProductEventDetail", ) - - event_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - + event_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) event_source = 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 @@ -166,20 +157,15 @@ class UserInfo(proto.Message): processing and pushing the user events). """ - visitor_id = proto.Field(proto.STRING, number=1) - - user_id = proto.Field(proto.STRING, number=2) - - ip_address = proto.Field(proto.STRING, number=3) - - user_agent = proto.Field(proto.STRING, number=4) - - direct_user_request = proto.Field(proto.BOOL, number=5) + visitor_id = proto.Field(proto.STRING, number=1,) + user_id = proto.Field(proto.STRING, number=2,) + ip_address = proto.Field(proto.STRING, number=3,) + user_agent = proto.Field(proto.STRING, number=4,) + direct_user_request = 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) @@ -234,16 +220,11 @@ class EventDetail(proto.Message): directly, or coming through Google search, and etc. """ - uri = proto.Field(proto.STRING, number=1) - - referrer_uri = proto.Field(proto.STRING, number=6) - - page_view_id = proto.Field(proto.STRING, number=2) - - experiment_ids = proto.RepeatedField(proto.STRING, number=3) - - recommendation_token = proto.Field(proto.STRING, number=4) - + uri = proto.Field(proto.STRING, number=1,) + referrer_uri = proto.Field(proto.STRING, number=6,) + page_view_id = proto.Field(proto.STRING, number=2,) + experiment_ids = proto.RepeatedField(proto.STRING, number=3,) + recommendation_token = proto.Field(proto.STRING, number=4,) event_attributes = proto.Field(proto.MESSAGE, number=5, message=common.FeatureMap,) @@ -309,20 +290,15 @@ class ProductEventDetail(proto.Message): should not set this field. """ - search_query = proto.Field(proto.STRING, number=1) - + search_query = proto.Field(proto.STRING, number=1,) page_categories = proto.RepeatedField( proto.MESSAGE, number=2, message=catalog.CatalogItem.CategoryHierarchy, ) - product_details = proto.RepeatedField( proto.MESSAGE, number=3, message="ProductDetail", ) - - list_id = proto.Field(proto.STRING, number=4) - - cart_id = proto.Field(proto.STRING, number=5) - + list_id = proto.Field(proto.STRING, number=4,) + cart_id = proto.Field(proto.STRING, number=5,) purchase_transaction = proto.Field( proto.MESSAGE, number=6, message="PurchaseTransaction", ) @@ -330,7 +306,6 @@ class ProductEventDetail(proto.Message): class PurchaseTransaction(proto.Message): r"""A transaction represents the entire purchase transaction. - Attributes: id (str): Optional. The transaction ID with a length @@ -361,20 +336,15 @@ class PurchaseTransaction(proto.Message): This field is not required if the event type is ``refund``. """ - id = proto.Field(proto.STRING, number=1) - - revenue = proto.Field(proto.FLOAT, number=2) - - taxes = proto.MapField(proto.STRING, proto.FLOAT, number=3) - - costs = proto.MapField(proto.STRING, proto.FLOAT, number=4) - - currency_code = proto.Field(proto.STRING, number=6) + id = proto.Field(proto.STRING, number=1,) + revenue = proto.Field(proto.FLOAT, number=2,) + taxes = proto.MapField(proto.STRING, proto.FLOAT, number=3,) + costs = proto.MapField(proto.STRING, proto.FLOAT, number=4,) + currency_code = 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 @@ -418,22 +388,15 @@ class ProductDetail(proto.Message): product in the user event. """ - id = proto.Field(proto.STRING, number=1) - - currency_code = proto.Field(proto.STRING, number=2) - - original_price = proto.Field(proto.FLOAT, number=3) - - display_price = proto.Field(proto.FLOAT, number=4) - + id = proto.Field(proto.STRING, number=1,) + currency_code = proto.Field(proto.STRING, number=2,) + original_price = proto.Field(proto.FLOAT, number=3,) + display_price = proto.Field(proto.FLOAT, number=4,) stock_state = proto.Field( proto.ENUM, number=5, enum=catalog.ProductCatalogItem.StockState, ) - - quantity = proto.Field(proto.INT32, number=6) - - available_quantity = proto.Field(proto.INT32, number=7) - + quantity = proto.Field(proto.INT32, number=6,) + available_quantity = proto.Field(proto.INT32, number=7,) item_attributes = proto.Field(proto.MESSAGE, number=8, message=common.FeatureMap,) diff --git a/google/cloud/recommendationengine_v1beta1/types/user_event_service.py b/google/cloud/recommendationengine_v1beta1/types/user_event_service.py index fce9b154..717f76d3 100644 --- a/google/cloud/recommendationengine_v1beta1/types/user_event_service.py +++ b/google/cloud/recommendationengine_v1beta1/types/user_event_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.recommendationengine_v1beta1.types import user_event as gcr_user_event -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -38,12 +35,11 @@ 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}". + ``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 @@ -71,11 +67,9 @@ class PurgeUserEventsRequest(proto.Message): returned. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - force = proto.Field(proto.BOOL, number=3) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + force = proto.Field(proto.BOOL, number=3,) class PurgeUserEventsMetadata(proto.Message): @@ -90,9 +84,8 @@ class PurgeUserEventsMetadata(proto.Message): Operation create time. """ - operation_name = proto.Field(proto.STRING, number=1) - - create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + operation_name = proto.Field(proto.STRING, number=1,) + create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) class PurgeUserEventsResponse(proto.Message): @@ -110,8 +103,7 @@ class PurgeUserEventsResponse(proto.Message): will be returned. """ - purged_events_count = proto.Field(proto.INT64, number=1) - + purged_events_count = proto.Field(proto.INT64, number=1,) user_events_sample = proto.RepeatedField( proto.MESSAGE, number=2, message=gcr_user_event.UserEvent, ) @@ -119,27 +111,24 @@ class PurgeUserEventsResponse(proto.Message): 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". + ``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 = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) user_event = proto.Field(proto.MESSAGE, number=2, message=gcr_user_event.UserEvent,) class CollectUserEventRequest(proto.Message): r"""Request message for CollectUserEvent method. - Attributes: parent (str): Required. The parent eventStore name, such as - "projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store". + ``projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store``. user_event (str): Required. URL encoded UserEvent proto. uri (str): @@ -156,22 +145,18 @@ class CollectUserEventRequest(proto.Message): abbreviated to reduce the payload bytes. """ - parent = proto.Field(proto.STRING, number=1) - - user_event = proto.Field(proto.STRING, number=2) - - uri = proto.Field(proto.STRING, number=3) - - ets = proto.Field(proto.INT64, number=4) + parent = proto.Field(proto.STRING, number=1,) + user_event = proto.Field(proto.STRING, number=2,) + uri = proto.Field(proto.STRING, number=3,) + ets = proto.Field(proto.INT64, number=4,) class 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`` + ``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 @@ -218,18 +203,14 @@ class ListUserEventsRequest(proto.Message): - Example 6: eventsMissingCatalogItems """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListUserEventsResponse(proto.Message): r"""Response message for ListUserEvents method. - Attributes: user_events (Sequence[google.cloud.recommendationengine_v1beta1.types.UserEvent]): The user events. @@ -245,8 +226,7 @@ def raw_page(self): user_events = proto.RepeatedField( proto.MESSAGE, number=1, message=gcr_user_event.UserEvent, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/noxfile.py b/noxfile.py index 43dd3024..03aa2f58 100644 --- a/noxfile.py +++ b/noxfile.py @@ -62,16 +62,9 @@ def lint(session): session.run("flake8", "google", "tests") -@nox.session(python="3.6") +@nox.session(python=DEFAULT_PYTHON_VERSION) def blacken(session): - """Run black. - - Format code to uniform standard. - - This currently uses Python 3.6 due to the automated Kokoro run of synthtool. - That run uses an image that doesn't have 3.6 installed. Before updating this - check the state of the `gcp_ubuntu_config` we use for that Kokoro run. - """ + """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) session.run( "black", *BLACK_PATHS, @@ -131,9 +124,6 @@ def system(session): # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Sanity check: Only run tests if the environment variable is set. - if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): - session.skip("Credentials must be set via environment variable") # Install pyopenssl for mTLS testing. if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": session.install("pyopenssl") @@ -189,7 +179,7 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx", "alabaster", "recommonmark") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -211,9 +201,9 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - # sphinx-docfx-yaml supports up to sphinx version 1.5.5. - # https://github.com/docascode/sphinx-docfx-yaml/issues/97 - session.install("sphinx==1.5.5", "alabaster", "recommonmark", "sphinx-docfx-yaml") + session.install( + "sphinx==4.0.1", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml" + ) shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/owlbot.py b/owlbot.py new file mode 100644 index 00000000..68c2a481 --- /dev/null +++ b/owlbot.py @@ -0,0 +1,101 @@ +# 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""This script is used to synthesize generated parts of this library.""" +import os +import re + +import synthtool as s +import synthtool.gcp as gcp +from synthtool.languages import python + +common = gcp.CommonTemplates() + +default_version = "v1beta1" + +for library in s.get_staging_dirs(default_version): + # rename library to recommendations ai, to be consistent with product branding + s.replace( + [library / "google/**/*.py", library / "tests/**/*.py"], + "google-cloud-recommendationengine", + "google-cloud-recommendations-ai", + ) + + # surround path with * with `` + s.replace(library / "google/**/*.py", """"(projects/\*/.*)"\.""", "``\g<1>``") + + s.replace( + library / "google/**/*client.py", + '''"projects/\*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/\"''', + """``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/``""" + ) + + s.replace( + library / "google/**/import_.py", + "gs://bucket/directory/\*\.json", + "``gs://bucket/directory/*.json``", + ) + + # Delete broken path helper 'catalog_item_path_path' + # https://github.com/googleapis/gapic-generator-python/issues/701 + s.replace( + library / "google/**/client.py", + """\s+@staticmethod +\s+def catalog_item_path_path.*? +\s+return m\.groupdict\(\) if m else \{\}\n""", + "", + flags=re.MULTILINE | re.DOTALL, + ) + + s.replace( + library / "google/**/async_client.py", + """parse_catalog_item_path_path =.*?\)""", + "", + flags=re.MULTILINE | re.DOTALL, + ) + + s.replace( + library / "google/**/async_client.py", + """catalog_item_path_path =.*?\)""", + "", + flags=re.MULTILINE | re.DOTALL, + ) + + # Delete unit tests for 'catalog_item_path_path' + s.replace( + library / "tests/**/test_catalog_service.py", + """def test_catalog_item_path_path.*?assert expected == actual""", + "", + flags=re.MULTILINE | re.DOTALL, + ) + + s.replace( + library / "tests/**/test_catalog_service.py", + """def test_parse_catalog_item_path_path.*?assert expected == actual""", + "", + flags=re.MULTILINE | re.DOTALL, + ) + + s.move(library, excludes=["setup.py", "docs/index.rst", "README.rst"]) + +s.remove_staging_dirs() +# ---------------------------------------------------------------------------- +# Add templated files +# ---------------------------------------------------------------------------- +templated_files = common.py_library(cov_level=98, microgenerator=True) +s.move( + templated_files, excludes=[".coveragerc"] +) # the microgenerator has a good coveragerc file + +s.shell.run(["nox", "-s", "blacken"], hide_output=False) \ No newline at end of file diff --git a/renovate.json b/renovate.json index f08bc22c..c0489556 100644 --- a/renovate.json +++ b/renovate.json @@ -2,5 +2,8 @@ "extends": [ "config:base", ":preserveSemverRanges" ], - "ignorePaths": [".pre-commit-config.yaml"] + "ignorePaths": [".pre-commit-config.yaml"], + "pip_requirements": { + "fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"] + } } diff --git a/scripts/fixup_recommendationengine_v1beta1_keywords.py b/scripts/fixup_recommendationengine_v1beta1_keywords.py index 15ac8f30..9652c971 100644 --- a/scripts/fixup_recommendationengine_v1beta1_keywords.py +++ b/scripts/fixup_recommendationengine_v1beta1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,22 +39,21 @@ def partition( 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', ), - + '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: @@ -87,7 +84,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +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 diff --git a/setup.py b/setup.py index ffa79be0..f8f11cf1 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ import os import setuptools # type: ignore -version = "0.2.0" +version = "0.2.1" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -42,6 +42,7 @@ install_requires=( "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "proto-plus >= 1.15.0", + "packaging >= 14.3", ), python_requires=">=3.6", classifiers=[ diff --git a/synth.metadata b/synth.metadata deleted file mode 100644 index 83c6880b..00000000 --- a/synth.metadata +++ /dev/null @@ -1,44 +0,0 @@ -{ - "sources": [ - { - "git": { - "name": ".", - "remote": "git@github.com:googleapis/python-recommendations-ai", - "sha": "6c6581870702de9834b39ef63b66ee3b1acf13c7" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "c0507a2bf28ea9f9af82559f2c876d2af598d6d9", - "internalRef": "365593953" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "60fc32cc950c20cfdd774b846a4a7dc5d1e4d0ef" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "60fc32cc950c20cfdd774b846a4a7dc5d1e4d0ef" - } - } - ], - "destinations": [ - { - "client": { - "source": "googleapis", - "apiName": "recommendationengine", - "apiVersion": "v1beta1", - "language": "python", - "generator": "bazel" - } - } - ] -} \ No newline at end of file diff --git a/synth.py b/synth.py deleted file mode 100644 index d1a21752..00000000 --- a/synth.py +++ /dev/null @@ -1,107 +0,0 @@ -# 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This script is used to synthesize generated parts of this library.""" -import os -import re - -import synthtool as s -import synthtool.gcp as gcp -from synthtool.languages import python - -gapic = gcp.GAPICBazel() -common = gcp.CommonTemplates() - -# ---------------------------------------------------------------------------- -# Generate Recommendations AI GAPIC layer -# ---------------------------------------------------------------------------- -library = gapic.py_library( - service="recommendationengine", - version="v1beta1", - bazel_target="//google/cloud/recommendationengine/v1beta1:recommendationengine-v1beta1-py", -) - -s.move(library, excludes=["setup.py", "docs/index.rst", "README.rst"]) - - -# rename library to recommendations ai, to be consistent with product branding -s.replace( - ["google/**/*.py", "tests/**/*.py"], - "google-cloud-recommendationengine", - "google-cloud-recommendations-ai", -) - -# surround path with * with `` -s.replace("google/**/*.py", """"(projects/\*/.*)"\.""", "``\g<1>``") -s.replace( - "google/**/*client.py", - '''"projects/\*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/\"''', - """``projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/``""" -) -s.replace( - "google/**/import_.py", - "gs://bucket/directory/\*\.json", - "``gs://bucket/directory/*.json``", -) - - -# Delete broken path helper 'catalog_item_path_path' -# https://github.com/googleapis/gapic-generator-python/issues/701 -s.replace( - "google/**/client.py", - """\s+@staticmethod -\s+def catalog_item_path_path.*? -\s+return m\.groupdict\(\) if m else \{\} -""", - "", - flags=re.MULTILINE | re.DOTALL, -) - -s.replace( - "google/**/async_client.py", - """parse_catalog_item_path_path =.*?\)""", - "", - flags=re.MULTILINE | re.DOTALL, -) -s.replace( - "google/**/async_client.py", - """catalog_item_path_path =.*?\)""", - "", - flags=re.MULTILINE | re.DOTALL, -) - -# Delete unit tests for 'catalog_item_path_path' -s.replace( - "tests/**/test_catalog_service.py", - """def test_catalog_item_path_path.*?assert expected == actual""", - "", - flags=re.MULTILINE | re.DOTALL, -) - -s.replace( - "tests/**/test_catalog_service.py", - """def test_parse_catalog_item_path_path.*?assert expected == actual""", - "", - flags=re.MULTILINE | re.DOTALL, -) - -# ---------------------------------------------------------------------------- -# Add templated files -# ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=98, microgenerator=True) -s.move( - templated_files, excludes=[".coveragerc"] -) # the microgenerator has a good coveragerc file - -s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index a9297012..b664e31a 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -7,3 +7,4 @@ # Then this file should have google-cloud-foo==1.14.0 google-api-core==1.22.2 proto-plus==1.15.0 +packaging==14.3 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/tests/unit/gapic/recommendationengine_v1beta1/__init__.py b/tests/unit/gapic/recommendationengine_v1beta1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/__init__.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py b/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py index cfa8391b..1180c79b 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,16 +23,16 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +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_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.recommendationengine_v1beta1.services.catalog_service import ( CatalogServiceAsyncClient, @@ -45,6 +44,12 @@ from google.cloud.recommendationengine_v1beta1.services.catalog_service import ( transports, ) +from google.cloud.recommendationengine_v1beta1.services.catalog_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.recommendationengine_v1beta1.services.catalog_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) 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 @@ -52,8 +57,32 @@ 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 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -104,7 +133,7 @@ def test__get_default_mtls_endpoint(): "client_class", [CatalogServiceClient, CatalogServiceAsyncClient,] ) def test_catalog_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -121,7 +150,7 @@ def test_catalog_service_client_from_service_account_info(client_class): "client_class", [CatalogServiceClient, CatalogServiceAsyncClient,] ) def test_catalog_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -174,7 +203,7 @@ def test_catalog_service_client_client_options( ): # 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=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -462,7 +491,7 @@ def test_create_catalog_item( transport: str = "grpc", request_type=catalog_service.CreateCatalogItemRequest ): client = CatalogServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -485,29 +514,20 @@ def test_create_catalog_item( 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" @@ -519,7 +539,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -529,7 +549,6 @@ def test_create_catalog_item_empty_call(): client.create_catalog_item() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.CreateCatalogItemRequest() @@ -539,7 +558,7 @@ async def test_create_catalog_item_async( request_type=catalog_service.CreateCatalogItemRequest, ): client = CatalogServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -561,28 +580,20 @@ async def test_create_catalog_item_async( 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" @@ -592,11 +603,12 @@ async def test_create_catalog_item_async_from_dict(): def test_create_catalog_item_field_headers(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -604,7 +616,6 @@ def test_create_catalog_item_field_headers(): 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. @@ -619,11 +630,14 @@ def test_create_catalog_item_field_headers(): @pytest.mark.asyncio async def test_create_catalog_item_field_headers_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -631,7 +645,6 @@ async def test_create_catalog_item_field_headers_async(): 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. @@ -645,7 +658,7 @@ async def test_create_catalog_item_field_headers_async(): def test_create_catalog_item_flattened(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -653,7 +666,6 @@ def test_create_catalog_item_flattened(): ) 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( @@ -664,14 +676,12 @@ def test_create_catalog_item_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].catalog_item == catalog.CatalogItem(id="id_value") def test_create_catalog_item_flattened_error(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -685,7 +695,9 @@ def test_create_catalog_item_flattened_error(): @pytest.mark.asyncio async def test_create_catalog_item_flattened_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -705,15 +717,15 @@ async def test_create_catalog_item_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].catalog_item == catalog.CatalogItem(id="id_value") @pytest.mark.asyncio async def test_create_catalog_item_flattened_error_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -729,7 +741,7 @@ def test_get_catalog_item( transport: str = "grpc", request_type=catalog_service.GetCatalogItemRequest ): client = CatalogServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -750,29 +762,20 @@ def test_get_catalog_item( 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" @@ -784,7 +787,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -792,7 +795,6 @@ def test_get_catalog_item_empty_call(): client.get_catalog_item() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.GetCatalogItemRequest() @@ -801,7 +803,7 @@ async def test_get_catalog_item_async( transport: str = "grpc_asyncio", request_type=catalog_service.GetCatalogItemRequest ): client = CatalogServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -821,28 +823,20 @@ async def test_get_catalog_item_async( 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" @@ -852,17 +846,17 @@ async def test_get_catalog_item_async_from_dict(): def test_get_catalog_item_field_headers(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -877,17 +871,19 @@ def test_get_catalog_item_field_headers(): @pytest.mark.asyncio async def test_get_catalog_item_field_headers_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -901,13 +897,12 @@ async def test_get_catalog_item_field_headers_async(): def test_get_catalog_item_flattened(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + 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",) @@ -916,12 +911,11 @@ def test_get_catalog_item_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_catalog_item_flattened_error(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -933,7 +927,9 @@ def test_get_catalog_item_flattened_error(): @pytest.mark.asyncio async def test_get_catalog_item_flattened_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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: @@ -949,13 +945,14 @@ async def test_get_catalog_item_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_catalog_item_flattened_error_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -969,7 +966,7 @@ def test_list_catalog_items( transport: str = "grpc", request_type=catalog_service.ListCatalogItemsRequest ): client = CatalogServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -984,19 +981,15 @@ def test_list_catalog_items( 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" @@ -1008,7 +1001,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1018,7 +1011,6 @@ def test_list_catalog_items_empty_call(): client.list_catalog_items() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.ListCatalogItemsRequest() @@ -1028,7 +1020,7 @@ async def test_list_catalog_items_async( request_type=catalog_service.ListCatalogItemsRequest, ): client = CatalogServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1045,18 +1037,15 @@ async def test_list_catalog_items_async( 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" @@ -1066,11 +1055,12 @@ async def test_list_catalog_items_async_from_dict(): def test_list_catalog_items_field_headers(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1078,7 +1068,6 @@ def test_list_catalog_items_field_headers(): 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. @@ -1093,11 +1082,14 @@ def test_list_catalog_items_field_headers(): @pytest.mark.asyncio async def test_list_catalog_items_field_headers_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1107,7 +1099,6 @@ async def test_list_catalog_items_field_headers_async(): 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. @@ -1121,7 +1112,7 @@ async def test_list_catalog_items_field_headers_async(): def test_list_catalog_items_flattened(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1129,7 +1120,6 @@ def test_list_catalog_items_flattened(): ) 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( @@ -1140,14 +1130,12 @@ def test_list_catalog_items_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].filter == "filter_value" def test_list_catalog_items_flattened_error(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1161,7 +1149,9 @@ def test_list_catalog_items_flattened_error(): @pytest.mark.asyncio async def test_list_catalog_items_flattened_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1183,15 +1173,15 @@ async def test_list_catalog_items_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].filter == "filter_value" @pytest.mark.asyncio async def test_list_catalog_items_flattened_error_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1204,7 +1194,7 @@ async def test_list_catalog_items_flattened_error_async(): def test_list_catalog_items_pager(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials,) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1246,7 +1236,7 @@ def test_list_catalog_items_pager(): def test_list_catalog_items_pages(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials,) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1280,7 +1270,7 @@ def test_list_catalog_items_pages(): @pytest.mark.asyncio async def test_list_catalog_items_async_pager(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CatalogServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1321,7 +1311,7 @@ async def test_list_catalog_items_async_pager(): @pytest.mark.asyncio async def test_list_catalog_items_async_pages(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CatalogServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1361,7 +1351,7 @@ def test_update_catalog_item( transport: str = "grpc", request_type=catalog_service.UpdateCatalogItemRequest ): client = CatalogServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1384,29 +1374,20 @@ def test_update_catalog_item( 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" @@ -1418,7 +1399,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1428,7 +1409,6 @@ def test_update_catalog_item_empty_call(): client.update_catalog_item() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.UpdateCatalogItemRequest() @@ -1438,7 +1418,7 @@ async def test_update_catalog_item_async( request_type=catalog_service.UpdateCatalogItemRequest, ): client = CatalogServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1460,28 +1440,20 @@ async def test_update_catalog_item_async( 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" @@ -1491,11 +1463,12 @@ async def test_update_catalog_item_async_from_dict(): def test_update_catalog_item_field_headers(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1503,7 +1476,6 @@ def test_update_catalog_item_field_headers(): 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. @@ -1518,11 +1490,14 @@ def test_update_catalog_item_field_headers(): @pytest.mark.asyncio async def test_update_catalog_item_field_headers_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1530,7 +1505,6 @@ async def test_update_catalog_item_field_headers_async(): 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. @@ -1544,7 +1518,7 @@ async def test_update_catalog_item_field_headers_async(): def test_update_catalog_item_flattened(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1552,29 +1526,25 @@ def test_update_catalog_item_flattened(): ) 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.FieldMask(paths=["paths_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] - assert args[0].name == "name_value" - assert args[0].catalog_item == catalog.CatalogItem(id="id_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_catalog_item_flattened_error(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1583,13 +1553,15 @@ def test_update_catalog_item_flattened_error(): catalog_service.UpdateCatalogItemRequest(), name="name_value", catalog_item=catalog.CatalogItem(id="id_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_catalog_item_flattened_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1604,24 +1576,23 @@ async def test_update_catalog_item_flattened_async(): response = await client.update_catalog_item( name="name_value", catalog_item=catalog.CatalogItem(id="id_value"), - update_mask=field_mask.FieldMask(paths=["paths_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] - assert args[0].name == "name_value" - assert args[0].catalog_item == catalog.CatalogItem(id="id_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_catalog_item_flattened_error_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1630,7 +1601,7 @@ async def test_update_catalog_item_flattened_error_async(): catalog_service.UpdateCatalogItemRequest(), name="name_value", catalog_item=catalog.CatalogItem(id="id_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1638,7 +1609,7 @@ def test_delete_catalog_item( transport: str = "grpc", request_type=catalog_service.DeleteCatalogItemRequest ): client = CatalogServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1651,13 +1622,11 @@ def test_delete_catalog_item( ) 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. @@ -1672,7 +1641,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1682,7 +1651,6 @@ def test_delete_catalog_item_empty_call(): client.delete_catalog_item() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == catalog_service.DeleteCatalogItemRequest() @@ -1692,7 +1660,7 @@ async def test_delete_catalog_item_async( request_type=catalog_service.DeleteCatalogItemRequest, ): client = CatalogServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1705,13 +1673,11 @@ async def test_delete_catalog_item_async( ) 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. @@ -1724,11 +1690,12 @@ async def test_delete_catalog_item_async_from_dict(): def test_delete_catalog_item_field_headers(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1736,7 +1703,6 @@ def test_delete_catalog_item_field_headers(): 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. @@ -1751,11 +1717,14 @@ def test_delete_catalog_item_field_headers(): @pytest.mark.asyncio async def test_delete_catalog_item_field_headers_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1763,7 +1732,6 @@ async def test_delete_catalog_item_field_headers_async(): 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. @@ -1777,7 +1745,7 @@ async def test_delete_catalog_item_field_headers_async(): def test_delete_catalog_item_flattened(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1785,7 +1753,6 @@ def test_delete_catalog_item_flattened(): ) 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",) @@ -1794,12 +1761,11 @@ def test_delete_catalog_item_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_catalog_item_flattened_error(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1811,7 +1777,9 @@ def test_delete_catalog_item_flattened_error(): @pytest.mark.asyncio async def test_delete_catalog_item_flattened_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1829,13 +1797,14 @@ async def test_delete_catalog_item_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_catalog_item_flattened_error_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1849,7 +1818,7 @@ def test_import_catalog_items( transport: str = "grpc", request_type=import_.ImportCatalogItemsRequest ): client = CatalogServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1862,13 +1831,11 @@ def test_import_catalog_items( ) 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. @@ -1883,7 +1850,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1893,7 +1860,6 @@ def test_import_catalog_items_empty_call(): client.import_catalog_items() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == import_.ImportCatalogItemsRequest() @@ -1902,7 +1868,7 @@ async def test_import_catalog_items_async( transport: str = "grpc_asyncio", request_type=import_.ImportCatalogItemsRequest ): client = CatalogServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1917,13 +1883,11 @@ async def test_import_catalog_items_async( 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. @@ -1936,11 +1900,12 @@ async def test_import_catalog_items_async_from_dict(): def test_import_catalog_items_field_headers(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1948,7 +1913,6 @@ def test_import_catalog_items_field_headers(): 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. @@ -1963,11 +1927,14 @@ def test_import_catalog_items_field_headers(): @pytest.mark.asyncio async def test_import_catalog_items_field_headers_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1977,7 +1944,6 @@ async def test_import_catalog_items_field_headers_async(): 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. @@ -1991,7 +1957,7 @@ async def test_import_catalog_items_field_headers_async(): def test_import_catalog_items_flattened(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1999,7 +1965,6 @@ def test_import_catalog_items_flattened(): ) 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( @@ -2017,24 +1982,20 @@ def test_import_catalog_items_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].request_id == "request_id_value" - assert args[0].input_config == import_.InputConfig( catalog_inline_source=import_.CatalogInlineSource( catalog_items=[catalog.CatalogItem(id="id_value")] ) ) - assert args[0].errors_config == import_.ImportErrorsConfig( gcs_prefix="gcs_prefix_value" ) def test_import_catalog_items_flattened_error(): - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2054,7 +2015,9 @@ def test_import_catalog_items_flattened_error(): @pytest.mark.asyncio async def test_import_catalog_items_flattened_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2083,17 +2046,13 @@ async def test_import_catalog_items_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].request_id == "request_id_value" - assert args[0].input_config == import_.InputConfig( catalog_inline_source=import_.CatalogInlineSource( catalog_items=[catalog.CatalogItem(id="id_value")] ) ) - assert args[0].errors_config == import_.ImportErrorsConfig( gcs_prefix="gcs_prefix_value" ) @@ -2101,7 +2060,9 @@ async def test_import_catalog_items_flattened_async(): @pytest.mark.asyncio async def test_import_catalog_items_flattened_error_async(): - client = CatalogServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CatalogServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2122,16 +2083,16 @@ async def test_import_catalog_items_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.CatalogServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CatalogServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.CatalogServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CatalogServiceClient( @@ -2141,7 +2102,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.CatalogServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CatalogServiceClient( @@ -2152,7 +2113,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.CatalogServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = CatalogServiceClient(transport=transport) assert client.transport is transport @@ -2161,13 +2122,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.CatalogServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.CatalogServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2182,23 +2143,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = CatalogServiceClient(credentials=credentials.AnonymousCredentials(),) + 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(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.CatalogServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2210,7 +2171,7 @@ def test_catalog_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.CatalogServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2233,15 +2194,37 @@ def test_catalog_service_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_catalog_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_catalog_service_base_transport_with_credentials_file_old_google_auth(): + # 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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CatalogServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2254,19 +2237,33 @@ def test_catalog_service_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + 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 = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CatalogServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_catalog_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_catalog_service_auth_adc_old_google_auth(): + # 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=("https://www.googleapis.com/auth/cloud-platform",), @@ -2274,20 +2271,156 @@ def test_catalog_service_auth_adc(): ) -def test_catalog_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.CatalogServiceGrpcTransport, + transports.CatalogServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.CatalogServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + 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, + ], +) +@requires_google_auth_lt_1_25_0 +def test_catalog_service_transport_auth_adc_old_google_auth(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") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_catalog_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "recommendationengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CatalogServiceGrpcTransport, grpc_helpers), + (transports.CatalogServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_catalog_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2296,7 +2429,7 @@ def test_catalog_service_transport_auth_adc(): ], ) def test_catalog_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2335,7 +2468,7 @@ def test_catalog_service_grpc_transport_client_cert_source_for_mtls(transport_cl def test_catalog_service_host_no_port(): client = CatalogServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="recommendationengine.googleapis.com" ), @@ -2345,7 +2478,7 @@ def test_catalog_service_host_no_port(): def test_catalog_service_host_with_port(): client = CatalogServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="recommendationengine.googleapis.com:8000" ), @@ -2401,9 +2534,9 @@ def test_catalog_service_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2479,7 +2612,7 @@ def test_catalog_service_transport_channel_mtls_with_adc(transport_class): def test_catalog_service_grpc_lro_client(): client = CatalogServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2492,7 +2625,7 @@ def test_catalog_service_grpc_lro_client(): def test_catalog_service_grpc_lro_async_client(): client = CatalogServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2507,7 +2640,6 @@ def test_catalog_path(): project = "squid" location = "clam" catalog = "whelk" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}".format( project=project, location=location, catalog=catalog, ) @@ -2530,7 +2662,6 @@ def test_parse_catalog_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2551,7 +2682,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = CatalogServiceClient.common_folder_path(folder) assert expected == actual @@ -2570,7 +2700,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = CatalogServiceClient.common_organization_path(organization) assert expected == actual @@ -2589,7 +2718,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = CatalogServiceClient.common_project_path(project) assert expected == actual @@ -2609,7 +2737,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2636,7 +2763,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.CatalogServiceTransport, "_prep_wrapped_messages" ) as prep: client = CatalogServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2645,6 +2772,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = CatalogServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py b/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py index 0ba68a97..64648eab 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +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.auth import credentials +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, @@ -44,10 +43,40 @@ from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import ( transports, ) +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.recommendationengine_v1beta1.types import ( prediction_apikey_registry_service, ) from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -100,7 +129,7 @@ def test__get_default_mtls_endpoint(): [PredictionApiKeyRegistryClient, PredictionApiKeyRegistryAsyncClient,], ) def test_prediction_api_key_registry_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -118,7 +147,7 @@ def test_prediction_api_key_registry_client_from_service_account_info(client_cla [PredictionApiKeyRegistryClient, PredictionApiKeyRegistryAsyncClient,], ) def test_prediction_api_key_registry_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -177,7 +206,7 @@ def test_prediction_api_key_registry_client_client_options( with mock.patch.object( PredictionApiKeyRegistryClient, "get_transport_class" ) as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -486,7 +515,7 @@ def test_create_prediction_api_key_registration( request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, ): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -501,24 +530,20 @@ def test_create_prediction_api_key_registration( 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" @@ -530,7 +555,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -540,7 +565,6 @@ def test_create_prediction_api_key_registration_empty_call(): client.create_prediction_api_key_registration() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( args[0] == prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() @@ -553,7 +577,7 @@ async def test_create_prediction_api_key_registration_async( request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, ): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -570,13 +594,11 @@ async def test_create_prediction_api_key_registration_async( 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() @@ -586,7 +608,6 @@ async def test_create_prediction_api_key_registration_async( assert isinstance( response, prediction_apikey_registry_service.PredictionApiKeyRegistration ) - assert response.api_key == "api_key_value" @@ -597,7 +618,7 @@ async def test_create_prediction_api_key_registration_async_from_dict(): def test_create_prediction_api_key_registration_field_headers(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -605,6 +626,7 @@ def test_create_prediction_api_key_registration_field_headers(): request = ( prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() ) + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -614,7 +636,6 @@ def test_create_prediction_api_key_registration_field_headers(): call.return_value = ( prediction_apikey_registry_service.PredictionApiKeyRegistration() ) - client.create_prediction_api_key_registration(request) # Establish that the underlying gRPC stub method was called. @@ -630,7 +651,7 @@ def test_create_prediction_api_key_registration_field_headers(): @pytest.mark.asyncio async def test_create_prediction_api_key_registration_field_headers_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -638,6 +659,7 @@ async def test_create_prediction_api_key_registration_field_headers_async(): request = ( prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest() ) + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -647,7 +669,6 @@ async def test_create_prediction_api_key_registration_field_headers_async(): 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. @@ -662,7 +683,7 @@ async def test_create_prediction_api_key_registration_field_headers_async(): def test_create_prediction_api_key_registration_flattened(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -673,7 +694,6 @@ def test_create_prediction_api_key_registration_flattened(): 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( @@ -687,9 +707,7 @@ def test_create_prediction_api_key_registration_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].prediction_api_key_registration == prediction_apikey_registry_service.PredictionApiKeyRegistration( @@ -699,7 +717,7 @@ def test_create_prediction_api_key_registration_flattened(): def test_create_prediction_api_key_registration_flattened_error(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -717,7 +735,7 @@ def test_create_prediction_api_key_registration_flattened_error(): @pytest.mark.asyncio async def test_create_prediction_api_key_registration_flattened_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -745,9 +763,7 @@ async def test_create_prediction_api_key_registration_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].prediction_api_key_registration == prediction_apikey_registry_service.PredictionApiKeyRegistration( @@ -758,7 +774,7 @@ async def test_create_prediction_api_key_registration_flattened_async(): @pytest.mark.asyncio async def test_create_prediction_api_key_registration_flattened_error_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -778,7 +794,7 @@ def test_list_prediction_api_key_registrations( request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, ): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -793,22 +809,18 @@ def test_list_prediction_api_key_registrations( 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" @@ -820,7 +832,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -830,7 +842,6 @@ def test_list_prediction_api_key_registrations_empty_call(): client.list_prediction_api_key_registrations() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( args[0] == prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() @@ -843,7 +854,7 @@ async def test_list_prediction_api_key_registrations_async( request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, ): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -860,13 +871,11 @@ async def test_list_prediction_api_key_registrations_async( 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() @@ -874,7 +883,6 @@ async def test_list_prediction_api_key_registrations_async( # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPredictionApiKeyRegistrationsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -885,7 +893,7 @@ async def test_list_prediction_api_key_registrations_async_from_dict(): def test_list_prediction_api_key_registrations_field_headers(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -893,6 +901,7 @@ def test_list_prediction_api_key_registrations_field_headers(): request = ( prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() ) + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -902,7 +911,6 @@ def test_list_prediction_api_key_registrations_field_headers(): call.return_value = ( prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsResponse() ) - client.list_prediction_api_key_registrations(request) # Establish that the underlying gRPC stub method was called. @@ -918,7 +926,7 @@ def test_list_prediction_api_key_registrations_field_headers(): @pytest.mark.asyncio async def test_list_prediction_api_key_registrations_field_headers_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -926,6 +934,7 @@ async def test_list_prediction_api_key_registrations_field_headers_async(): request = ( prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest() ) + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -935,7 +944,6 @@ async def test_list_prediction_api_key_registrations_field_headers_async(): 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. @@ -950,7 +958,7 @@ async def test_list_prediction_api_key_registrations_field_headers_async(): def test_list_prediction_api_key_registrations_flattened(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -961,7 +969,6 @@ def test_list_prediction_api_key_registrations_flattened(): 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",) @@ -970,13 +977,12 @@ def test_list_prediction_api_key_registrations_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_prediction_api_key_registrations_flattened_error(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -991,7 +997,7 @@ def test_list_prediction_api_key_registrations_flattened_error(): @pytest.mark.asyncio async def test_list_prediction_api_key_registrations_flattened_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1016,14 +1022,13 @@ async def test_list_prediction_api_key_registrations_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_prediction_api_key_registrations_flattened_error_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1037,7 +1042,7 @@ async def test_list_prediction_api_key_registrations_flattened_error_async(): def test_list_prediction_api_key_registrations_pager(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1092,7 +1097,7 @@ def test_list_prediction_api_key_registrations_pager(): def test_list_prediction_api_key_registrations_pages(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1134,7 +1139,7 @@ def test_list_prediction_api_key_registrations_pages(): @pytest.mark.asyncio async def test_list_prediction_api_key_registrations_async_pager(): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1188,7 +1193,7 @@ async def test_list_prediction_api_key_registrations_async_pager(): @pytest.mark.asyncio async def test_list_prediction_api_key_registrations_async_pages(): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1238,7 +1243,7 @@ def test_delete_prediction_api_key_registration( request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, ): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1251,13 +1256,11 @@ def test_delete_prediction_api_key_registration( ) 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() @@ -1275,7 +1278,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1285,7 +1288,6 @@ def test_delete_prediction_api_key_registration_empty_call(): client.delete_prediction_api_key_registration() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( args[0] == prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() @@ -1298,7 +1300,7 @@ async def test_delete_prediction_api_key_registration_async( request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, ): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1311,13 +1313,11 @@ async def test_delete_prediction_api_key_registration_async( ) 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() @@ -1334,7 +1334,7 @@ async def test_delete_prediction_api_key_registration_async_from_dict(): def test_delete_prediction_api_key_registration_field_headers(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1342,6 +1342,7 @@ def test_delete_prediction_api_key_registration_field_headers(): request = ( prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() ) + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1349,7 +1350,6 @@ def test_delete_prediction_api_key_registration_field_headers(): 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. @@ -1365,7 +1365,7 @@ def test_delete_prediction_api_key_registration_field_headers(): @pytest.mark.asyncio async def test_delete_prediction_api_key_registration_field_headers_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as @@ -1373,6 +1373,7 @@ async def test_delete_prediction_api_key_registration_field_headers_async(): request = ( prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest() ) + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1380,7 +1381,6 @@ async def test_delete_prediction_api_key_registration_field_headers_async(): 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. @@ -1395,7 +1395,7 @@ async def test_delete_prediction_api_key_registration_field_headers_async(): def test_delete_prediction_api_key_registration_flattened(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1404,7 +1404,6 @@ def test_delete_prediction_api_key_registration_flattened(): ) 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",) @@ -1413,13 +1412,12 @@ def test_delete_prediction_api_key_registration_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_prediction_api_key_registration_flattened_error(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1434,7 +1432,7 @@ def test_delete_prediction_api_key_registration_flattened_error(): @pytest.mark.asyncio async def test_delete_prediction_api_key_registration_flattened_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1455,14 +1453,13 @@ async def test_delete_prediction_api_key_registration_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_prediction_api_key_registration_flattened_error_async(): client = PredictionApiKeyRegistryAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1477,16 +1474,16 @@ async def test_delete_prediction_api_key_registration_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PredictionApiKeyRegistryClient( @@ -1496,7 +1493,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PredictionApiKeyRegistryClient( @@ -1507,7 +1504,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = PredictionApiKeyRegistryClient(transport=transport) assert client.transport is transport @@ -1516,13 +1513,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.PredictionApiKeyRegistryGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.PredictionApiKeyRegistryGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1537,8 +1534,8 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() @@ -1546,7 +1543,7 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) assert isinstance( client.transport, transports.PredictionApiKeyRegistryGrpcTransport, @@ -1555,9 +1552,9 @@ def test_transport_grpc_default(): def test_prediction_api_key_registry_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.PredictionApiKeyRegistryTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1569,7 +1566,7 @@ def test_prediction_api_key_registry_base_transport(): ) as Transport: Transport.return_value = None transport = transports.PredictionApiKeyRegistryTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1584,15 +1581,37 @@ def test_prediction_api_key_registry_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_prediction_api_key_registry_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_prediction_api_key_registry_base_transport_with_credentials_file_old_google_auth(): + # 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", ) @@ -1605,19 +1624,33 @@ def test_prediction_api_key_registry_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + 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 = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PredictionApiKeyRegistryTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_prediction_api_key_registry_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_prediction_api_key_registry_auth_adc_old_google_auth(): + # 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=("https://www.googleapis.com/auth/cloud-platform",), @@ -1625,20 +1658,160 @@ def test_prediction_api_key_registry_auth_adc(): ) -def test_prediction_api_key_registry_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.PredictionApiKeyRegistryGrpcTransport, + transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.PredictionApiKeyRegistryGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + 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, + ], +) +@requires_google_auth_lt_1_25_0 +def test_prediction_api_key_registry_transport_auth_adc_old_google_auth( + 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") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PredictionApiKeyRegistryGrpcTransport, grpc_helpers), + (transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.PredictionApiKeyRegistryGrpcTransport, grpc_helpers), + (transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_prediction_api_key_registry_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "recommendationengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PredictionApiKeyRegistryGrpcTransport, grpc_helpers), + (transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_prediction_api_key_registry_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1649,7 +1822,7 @@ def test_prediction_api_key_registry_transport_auth_adc(): def test_prediction_api_key_registry_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1688,7 +1861,7 @@ def test_prediction_api_key_registry_grpc_transport_client_cert_source_for_mtls( def test_prediction_api_key_registry_host_no_port(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="recommendationengine.googleapis.com" ), @@ -1698,7 +1871,7 @@ def test_prediction_api_key_registry_host_no_port(): def test_prediction_api_key_registry_host_with_port(): client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="recommendationengine.googleapis.com:8000" ), @@ -1754,9 +1927,9 @@ def test_prediction_api_key_registry_transport_channel_mtls_with_client_cert_sou mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1835,7 +2008,6 @@ def test_event_store_path(): 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, ) @@ -1865,7 +2037,6 @@ def test_prediction_api_key_registration_path(): 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, @@ -1900,7 +2071,6 @@ def test_parse_prediction_api_key_registration_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1921,7 +2091,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = PredictionApiKeyRegistryClient.common_folder_path(folder) assert expected == actual @@ -1940,7 +2109,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = PredictionApiKeyRegistryClient.common_organization_path(organization) assert expected == actual @@ -1959,7 +2127,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = PredictionApiKeyRegistryClient.common_project_path(project) assert expected == actual @@ -1979,7 +2146,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2006,7 +2172,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.PredictionApiKeyRegistryTransport, "_prep_wrapped_messages" ) as prep: client = PredictionApiKeyRegistryClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2015,6 +2181,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = PredictionApiKeyRegistryClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py b/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py index 2b191a45..3279292a 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +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.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( PredictionServiceAsyncClient, @@ -42,13 +41,43 @@ from google.cloud.recommendationengine_v1beta1.services.prediction_service import ( transports, ) +from google.cloud.recommendationengine_v1beta1.services.prediction_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.recommendationengine_v1beta1.services.prediction_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) 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 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -100,7 +129,7 @@ def test__get_default_mtls_endpoint(): "client_class", [PredictionServiceClient, PredictionServiceAsyncClient,] ) def test_prediction_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -117,7 +146,7 @@ def test_prediction_service_client_from_service_account_info(client_class): "client_class", [PredictionServiceClient, PredictionServiceAsyncClient,] ) def test_prediction_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -170,7 +199,7 @@ def test_prediction_service_client_client_options( ): # 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=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -468,7 +497,7 @@ def test_predict( transport: str = "grpc", request_type=prediction_service.PredictRequest ): client = PredictionServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -484,25 +513,18 @@ def test_predict( 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" @@ -514,7 +536,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -522,7 +544,6 @@ def test_predict_empty_call(): client.predict() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == prediction_service.PredictRequest() @@ -531,7 +552,7 @@ async def test_predict_async( transport: str = "grpc_asyncio", request_type=prediction_service.PredictRequest ): client = PredictionServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -549,24 +570,18 @@ async def test_predict_async( 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" @@ -576,17 +591,17 @@ async def test_predict_async_from_dict(): def test_predict_field_headers(): - client = PredictionServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -602,12 +617,13 @@ def test_predict_field_headers(): @pytest.mark.asyncio async def test_predict_field_headers_async(): client = PredictionServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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. @@ -615,7 +631,6 @@ async def test_predict_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( prediction_service.PredictResponse() ) - await client.predict(request) # Establish that the underlying gRPC stub method was called. @@ -629,13 +644,12 @@ async def test_predict_field_headers_async(): def test_predict_flattened(): - client = PredictionServiceClient(credentials=credentials.AnonymousCredentials(),) + 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( @@ -647,16 +661,14 @@ def test_predict_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].user_event == gcr_user_event.UserEvent( event_type="event_type_value" ) def test_predict_flattened_error(): - client = PredictionServiceClient(credentials=credentials.AnonymousCredentials(),) + client = PredictionServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -671,7 +683,7 @@ def test_predict_flattened_error(): @pytest.mark.asyncio async def test_predict_flattened_async(): client = PredictionServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -693,9 +705,7 @@ async def test_predict_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].user_event == gcr_user_event.UserEvent( event_type="event_type_value" ) @@ -704,7 +714,7 @@ async def test_predict_flattened_async(): @pytest.mark.asyncio async def test_predict_flattened_error_async(): client = PredictionServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -718,7 +728,7 @@ async def test_predict_flattened_error_async(): def test_predict_pager(): - client = PredictionServiceClient(credentials=credentials.AnonymousCredentials,) + 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: @@ -763,7 +773,7 @@ def test_predict_pager(): def test_predict_pages(): - client = PredictionServiceClient(credentials=credentials.AnonymousCredentials,) + 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: @@ -797,7 +807,9 @@ def test_predict_pages(): @pytest.mark.asyncio async def test_predict_async_pager(): - client = PredictionServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -841,7 +853,9 @@ async def test_predict_async_pager(): @pytest.mark.asyncio async def test_predict_async_pages(): - client = PredictionServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PredictionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -880,16 +894,16 @@ async def test_predict_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PredictionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PredictionServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.PredictionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PredictionServiceClient( @@ -899,7 +913,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.PredictionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PredictionServiceClient( @@ -910,7 +924,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.PredictionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = PredictionServiceClient(transport=transport) assert client.transport is transport @@ -919,13 +933,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.PredictionServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.PredictionServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -940,23 +954,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = PredictionServiceClient(credentials=credentials.AnonymousCredentials(),) + 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(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.PredictionServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -968,7 +982,7 @@ def test_prediction_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.PredictionServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -979,15 +993,37 @@ def test_prediction_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_prediction_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_prediction_service_base_transport_with_credentials_file_old_google_auth(): + # 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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PredictionServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1000,19 +1036,33 @@ def test_prediction_service_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + 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 = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PredictionServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_prediction_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_prediction_service_auth_adc_old_google_auth(): + # 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=("https://www.googleapis.com/auth/cloud-platform",), @@ -1020,20 +1070,156 @@ def test_prediction_service_auth_adc(): ) -def test_prediction_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.PredictionServiceGrpcTransport, + transports.PredictionServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.PredictionServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + 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, + ], +) +@requires_google_auth_lt_1_25_0 +def test_prediction_service_transport_auth_adc_old_google_auth(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") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_prediction_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "recommendationengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PredictionServiceGrpcTransport, grpc_helpers), + (transports.PredictionServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_prediction_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1042,7 +1228,7 @@ def test_prediction_service_transport_auth_adc(): ], ) def test_prediction_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1081,7 +1267,7 @@ def test_prediction_service_grpc_transport_client_cert_source_for_mtls(transport def test_prediction_service_host_no_port(): client = PredictionServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="recommendationengine.googleapis.com" ), @@ -1091,7 +1277,7 @@ def test_prediction_service_host_no_port(): def test_prediction_service_host_with_port(): client = PredictionServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="recommendationengine.googleapis.com:8000" ), @@ -1147,9 +1333,9 @@ def test_prediction_service_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1229,7 +1415,6 @@ def test_placement_path(): catalog = "whelk" event_store = "octopus" placement = "oyster" - expected = "projects/{project}/locations/{location}/catalogs/{catalog}/eventStores/{event_store}/placements/{placement}".format( project=project, location=location, @@ -1260,7 +1445,6 @@ def test_parse_placement_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1281,7 +1465,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = PredictionServiceClient.common_folder_path(folder) assert expected == actual @@ -1300,7 +1483,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = PredictionServiceClient.common_organization_path(organization) assert expected == actual @@ -1319,7 +1501,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = PredictionServiceClient.common_project_path(project) assert expected == actual @@ -1339,7 +1520,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1366,7 +1546,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.PredictionServiceTransport, "_prep_wrapped_messages" ) as prep: client = PredictionServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1375,6 +1555,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = PredictionServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py b/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py index b4753dde..81dfb489 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,17 +23,17 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth -from google.api import httpbody_pb2 as httpbody # type: ignore + +from google.api import httpbody_pb2 # type: ignore from google.api_core import client_options -from google.api_core import exceptions +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_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +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, @@ -46,6 +45,12 @@ from google.cloud.recommendationengine_v1beta1.services.user_event_service import ( transports, ) +from google.cloud.recommendationengine_v1beta1.services.user_event_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.recommendationengine_v1beta1.services.user_event_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.recommendationengine_v1beta1.types import catalog from google.cloud.recommendationengine_v1beta1.types import common from google.cloud.recommendationengine_v1beta1.types import import_ @@ -54,8 +59,32 @@ 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 as gp_any # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -107,7 +136,7 @@ def test__get_default_mtls_endpoint(): "client_class", [UserEventServiceClient, UserEventServiceAsyncClient,] ) def test_user_event_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -124,7 +153,7 @@ def test_user_event_service_client_from_service_account_info(client_class): "client_class", [UserEventServiceClient, UserEventServiceAsyncClient,] ) def test_user_event_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -177,7 +206,7 @@ def test_user_event_service_client_client_options( ): # 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=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -475,7 +504,7 @@ def test_write_user_event( transport: str = "grpc", request_type=user_event_service.WriteUserEventRequest ): client = UserEventServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -489,21 +518,16 @@ def test_write_user_event( 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 @@ -515,7 +539,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -523,7 +547,6 @@ def test_write_user_event_empty_call(): client.write_user_event() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() @@ -533,7 +556,7 @@ async def test_write_user_event_async( request_type=user_event_service.WriteUserEventRequest, ): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -549,20 +572,16 @@ async def test_write_user_event_async( 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 @@ -572,17 +591,17 @@ async def test_write_user_event_async_from_dict(): def test_write_user_event_field_headers(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -598,12 +617,13 @@ def test_write_user_event_field_headers(): @pytest.mark.asyncio async def test_write_user_event_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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. @@ -611,7 +631,6 @@ async def test_write_user_event_field_headers_async(): 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. @@ -625,13 +644,12 @@ async def test_write_user_event_field_headers_async(): def test_write_user_event_flattened(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + 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( @@ -643,16 +661,14 @@ def test_write_user_event_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].user_event == gcr_user_event.UserEvent( event_type="event_type_value" ) def test_write_user_event_flattened_error(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UserEventServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -667,7 +683,7 @@ def test_write_user_event_flattened_error(): @pytest.mark.asyncio async def test_write_user_event_flattened_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -689,9 +705,7 @@ async def test_write_user_event_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].user_event == gcr_user_event.UserEvent( event_type="event_type_value" ) @@ -700,7 +714,7 @@ async def test_write_user_event_flattened_async(): @pytest.mark.asyncio async def test_write_user_event_flattened_error_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -717,7 +731,7 @@ def test_collect_user_event( transport: str = "grpc", request_type=user_event_service.CollectUserEventRequest ): client = UserEventServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -729,24 +743,19 @@ def test_collect_user_event( type(client.transport.collect_user_event), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = httpbody.HttpBody( + 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.HttpBody) - + assert isinstance(response, httpbody_pb2.HttpBody) assert response.content_type == "content_type_value" - assert response.data == b"data_blob" @@ -758,7 +767,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -768,7 +777,6 @@ def test_collect_user_event_empty_call(): client.collect_user_event() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() @@ -778,7 +786,7 @@ async def test_collect_user_event_async( request_type=user_event_service.CollectUserEventRequest, ): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -791,22 +799,18 @@ async def test_collect_user_event_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - httpbody.HttpBody(content_type="content_type_value", data=b"data_blob",) + 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.HttpBody) - + assert isinstance(response, httpbody_pb2.HttpBody) assert response.content_type == "content_type_value" - assert response.data == b"data_blob" @@ -816,19 +820,19 @@ async def test_collect_user_event_async_from_dict(): def test_collect_user_event_field_headers(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + 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.HttpBody() - + call.return_value = httpbody_pb2.HttpBody() client.collect_user_event(request) # Establish that the underlying gRPC stub method was called. @@ -844,20 +848,22 @@ def test_collect_user_event_field_headers(): @pytest.mark.asyncio async def test_collect_user_event_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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.HttpBody()) - + 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. @@ -871,15 +877,14 @@ async def test_collect_user_event_field_headers_async(): def test_collect_user_event_flattened(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + 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.HttpBody() - + 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( @@ -893,18 +898,14 @@ def test_collect_user_event_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].user_event == "user_event_value" - assert args[0].uri == "uri_value" - assert args[0].ets == 332 def test_collect_user_event_flattened_error(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UserEventServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -921,7 +922,7 @@ def test_collect_user_event_flattened_error(): @pytest.mark.asyncio async def test_collect_user_event_flattened_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -929,9 +930,11 @@ async def test_collect_user_event_flattened_async(): type(client.transport.collect_user_event), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = httpbody.HttpBody() + call.return_value = httpbody_pb2.HttpBody() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody.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( @@ -945,20 +948,16 @@ async def test_collect_user_event_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].user_event == "user_event_value" - assert args[0].uri == "uri_value" - assert args[0].ets == 332 @pytest.mark.asyncio async def test_collect_user_event_flattened_error_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -977,7 +976,7 @@ def test_list_user_events( transport: str = "grpc", request_type=user_event_service.ListUserEventsRequest ): client = UserEventServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -990,19 +989,15 @@ def test_list_user_events( 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" @@ -1014,7 +1009,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1022,7 +1017,6 @@ def test_list_user_events_empty_call(): client.list_user_events() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.ListUserEventsRequest() @@ -1032,7 +1026,7 @@ async def test_list_user_events_async( request_type=user_event_service.ListUserEventsRequest, ): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1047,18 +1041,15 @@ async def test_list_user_events_async( 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" @@ -1068,17 +1059,17 @@ async def test_list_user_events_async_from_dict(): def test_list_user_events_field_headers(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1094,12 +1085,13 @@ def test_list_user_events_field_headers(): @pytest.mark.asyncio async def test_list_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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. @@ -1107,7 +1099,6 @@ async def test_list_user_events_field_headers_async(): 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. @@ -1121,13 +1112,12 @@ async def test_list_user_events_field_headers_async(): def test_list_user_events_flattened(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + 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( @@ -1138,14 +1128,12 @@ def test_list_user_events_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].filter == "filter_value" def test_list_user_events_flattened_error(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UserEventServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1160,7 +1148,7 @@ def test_list_user_events_flattened_error(): @pytest.mark.asyncio async def test_list_user_events_flattened_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1181,16 +1169,14 @@ async def test_list_user_events_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].filter == "filter_value" @pytest.mark.asyncio async def test_list_user_events_flattened_error_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1204,7 +1190,7 @@ async def test_list_user_events_flattened_error_async(): def test_list_user_events_pager(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials,) + 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: @@ -1244,7 +1230,7 @@ def test_list_user_events_pager(): def test_list_user_events_pages(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials,) + 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: @@ -1276,7 +1262,9 @@ def test_list_user_events_pages(): @pytest.mark.asyncio async def test_list_user_events_async_pager(): - client = UserEventServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1315,7 +1303,9 @@ async def test_list_user_events_async_pager(): @pytest.mark.asyncio async def test_list_user_events_async_pages(): - client = UserEventServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1353,7 +1343,7 @@ def test_purge_user_events( transport: str = "grpc", request_type=user_event_service.PurgeUserEventsRequest ): client = UserEventServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1366,13 +1356,11 @@ def test_purge_user_events( ) 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. @@ -1387,7 +1375,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1397,7 +1385,6 @@ def test_purge_user_events_empty_call(): client.purge_user_events() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.PurgeUserEventsRequest() @@ -1407,7 +1394,7 @@ async def test_purge_user_events_async( request_type=user_event_service.PurgeUserEventsRequest, ): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1422,13 +1409,11 @@ async def test_purge_user_events_async( 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. @@ -1441,11 +1426,12 @@ async def test_purge_user_events_async_from_dict(): def test_purge_user_events_field_headers(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1453,7 +1439,6 @@ def test_purge_user_events_field_headers(): 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. @@ -1469,12 +1454,13 @@ def test_purge_user_events_field_headers(): @pytest.mark.asyncio async def test_purge_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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. @@ -1484,7 +1470,6 @@ async def test_purge_user_events_field_headers_async(): 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. @@ -1498,7 +1483,7 @@ async def test_purge_user_events_field_headers_async(): def test_purge_user_events_flattened(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UserEventServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1506,7 +1491,6 @@ def test_purge_user_events_flattened(): ) 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( @@ -1517,16 +1501,13 @@ def test_purge_user_events_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].filter == "filter_value" - assert args[0].force == True def test_purge_user_events_flattened_error(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UserEventServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1542,7 +1523,7 @@ def test_purge_user_events_flattened_error(): @pytest.mark.asyncio async def test_purge_user_events_flattened_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1565,18 +1546,15 @@ async def test_purge_user_events_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].filter == "filter_value" - assert args[0].force == True @pytest.mark.asyncio async def test_purge_user_events_flattened_error_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1594,7 +1572,7 @@ def test_import_user_events( transport: str = "grpc", request_type=import_.ImportUserEventsRequest ): client = UserEventServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1607,13 +1585,11 @@ def test_import_user_events( ) 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. @@ -1628,7 +1604,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1638,7 +1614,6 @@ def test_import_user_events_empty_call(): client.import_user_events() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == import_.ImportUserEventsRequest() @@ -1647,7 +1622,7 @@ async def test_import_user_events_async( transport: str = "grpc_asyncio", request_type=import_.ImportUserEventsRequest ): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1662,13 +1637,11 @@ async def test_import_user_events_async( 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. @@ -1681,11 +1654,12 @@ async def test_import_user_events_async_from_dict(): def test_import_user_events_field_headers(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + 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. @@ -1693,7 +1667,6 @@ def test_import_user_events_field_headers(): 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. @@ -1709,12 +1682,13 @@ def test_import_user_events_field_headers(): @pytest.mark.asyncio async def test_import_user_events_field_headers_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Any value 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. @@ -1724,7 +1698,6 @@ async def test_import_user_events_field_headers_async(): 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. @@ -1738,7 +1711,7 @@ async def test_import_user_events_field_headers_async(): def test_import_user_events_flattened(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UserEventServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1746,7 +1719,6 @@ def test_import_user_events_flattened(): ) 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( @@ -1764,24 +1736,20 @@ def test_import_user_events_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].request_id == "request_id_value" - assert args[0].input_config == import_.InputConfig( catalog_inline_source=import_.CatalogInlineSource( catalog_items=[catalog.CatalogItem(id="id_value")] ) ) - assert args[0].errors_config == import_.ImportErrorsConfig( gcs_prefix="gcs_prefix_value" ) def test_import_user_events_flattened_error(): - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + client = UserEventServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1802,7 +1770,7 @@ def test_import_user_events_flattened_error(): @pytest.mark.asyncio async def test_import_user_events_flattened_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1832,17 +1800,13 @@ async def test_import_user_events_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].request_id == "request_id_value" - assert args[0].input_config == import_.InputConfig( catalog_inline_source=import_.CatalogInlineSource( catalog_items=[catalog.CatalogItem(id="id_value")] ) ) - assert args[0].errors_config == import_.ImportErrorsConfig( gcs_prefix="gcs_prefix_value" ) @@ -1851,7 +1815,7 @@ async def test_import_user_events_flattened_async(): @pytest.mark.asyncio async def test_import_user_events_flattened_error_async(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1873,16 +1837,16 @@ async def test_import_user_events_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.UserEventServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = UserEventServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.UserEventServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = UserEventServiceClient( @@ -1892,7 +1856,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.UserEventServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = UserEventServiceClient( @@ -1903,7 +1867,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.UserEventServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = UserEventServiceClient(transport=transport) assert client.transport is transport @@ -1912,13 +1876,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.UserEventServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1933,23 +1897,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = UserEventServiceClient(credentials=credentials.AnonymousCredentials(),) + 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(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.UserEventServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1961,7 +1925,7 @@ def test_user_event_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.UserEventServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1983,15 +1947,37 @@ def test_user_event_service_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_user_event_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + 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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_user_event_service_base_transport_with_credentials_file_old_google_auth(): + # 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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.UserEventServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2004,19 +1990,33 @@ def test_user_event_service_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + 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 = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.UserEventServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_user_event_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_user_event_service_auth_adc_old_google_auth(): + # 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=("https://www.googleapis.com/auth/cloud-platform",), @@ -2024,20 +2024,156 @@ def test_user_event_service_auth_adc(): ) -def test_user_event_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.UserEventServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + 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, + ], +) +@requires_google_auth_lt_1_25_0 +def test_user_event_service_transport_auth_adc_old_google_auth(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") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_user_event_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "recommendationengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_user_event_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2046,7 +2182,7 @@ def test_user_event_service_transport_auth_adc(): ], ) def test_user_event_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2085,7 +2221,7 @@ def test_user_event_service_grpc_transport_client_cert_source_for_mtls(transport def test_user_event_service_host_no_port(): client = UserEventServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="recommendationengine.googleapis.com" ), @@ -2095,7 +2231,7 @@ def test_user_event_service_host_no_port(): def test_user_event_service_host_with_port(): client = UserEventServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="recommendationengine.googleapis.com:8000" ), @@ -2151,9 +2287,9 @@ def test_user_event_service_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2229,7 +2365,7 @@ def test_user_event_service_transport_channel_mtls_with_adc(transport_class): def test_user_event_service_grpc_lro_client(): client = UserEventServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2242,7 +2378,7 @@ def test_user_event_service_grpc_lro_client(): def test_user_event_service_grpc_lro_async_client(): client = UserEventServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2258,7 +2394,6 @@ def test_event_store_path(): 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, ) @@ -2284,7 +2419,6 @@ def test_parse_event_store_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2305,7 +2439,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = UserEventServiceClient.common_folder_path(folder) assert expected == actual @@ -2324,7 +2457,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = UserEventServiceClient.common_organization_path(organization) assert expected == actual @@ -2343,7 +2475,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = UserEventServiceClient.common_project_path(project) assert expected == actual @@ -2363,7 +2494,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2390,7 +2520,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.UserEventServiceTransport, "_prep_wrapped_messages" ) as prep: client = UserEventServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2399,6 +2529,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = UserEventServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)