diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 108063d4..39ad3cec 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,16 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:4ee57a76a176ede9087c14330c625a71553cf9c72828b2c0ca12f5338171ba60 + digest: sha256:d22cd2ddce65fdac6986f115563faf2fc81482b09dfbea83ac2808c92ecfdff0 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 30c3973a..e446644f 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3,9 +3,10 @@ # # For syntax help see: # https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax +# Note: This file is autogenerated. To make changes to the codeowner team, please update .repo-metadata.json. -# The @googleapis/yoshi-python is the default owner for changes in this repo -* @googleapis/yoshi-python +# @googleapis/yoshi-python is the default owner for changes in this repo +* @googleapis/yoshi-python -# The python-samples-reviewers team is the default owner for samples changes -/samples/ @googleapis/python-samples-owners \ No newline at end of file +# @googleapis/python-samples-reviewers is the default owner for samples changes +/samples/ @googleapis/python-samples-reviewers diff --git a/.github/release-please.yml b/.github/release-please.yml index 4507ad05..466597e5 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1 +1,2 @@ releaseType: python +handleGHRelease: true diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml new file mode 100644 index 00000000..d4ca9418 --- /dev/null +++ b/.github/release-trigger.yml @@ -0,0 +1 @@ +enabled: true diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 00000000..f7b8344c --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,38 @@ +on: + pull_request: + branches: + - main +name: docs +jobs: + docs: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run docs + run: | + nox -s docs + docfx: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run docfx + run: | + nox -s docfx diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..1e8b05c3 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,25 @@ +on: + pull_request: + branches: + - main +name: lint +jobs: + lint: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run lint + run: | + nox -s lint + - name: Run lint_setup_py + run: | + nox -s lint_setup_py diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml new file mode 100644 index 00000000..074ee250 --- /dev/null +++ b/.github/workflows/unittest.yml @@ -0,0 +1,57 @@ +on: + pull_request: + branches: + - main +name: unittest +jobs: + unit: + runs-on: ubuntu-latest + strategy: + matrix: + python: ['3.6', '3.7', '3.8', '3.9', '3.10'] + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python }} + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run unit tests + env: + COVERAGE_FILE: .coverage-${{ matrix.python }} + run: | + nox -s unit-${{ matrix.python }} + - name: Upload coverage results + uses: actions/upload-artifact@v2 + with: + name: coverage-artifacts + path: .coverage-${{ matrix.python }} + + cover: + runs-on: ubuntu-latest + needs: + - unit + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install coverage + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install coverage + - name: Download coverage results + uses: actions/download-artifact@v2 + with: + name: coverage-artifacts + path: .coverage-results/ + - name: Report coverage results + run: | + coverage combine .coverage-results/.coverage* + coverage report --show-missing --fail-under=100 diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 225f6840..1ea9d9a2 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_GFILE_DIR}/secret_manager/google-cloud-pypi-token") +TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google-cloud-pypi-token-keystore-1") cd github/python-recommendations-ai python3 setup.py sdist bdist_wheel twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/* diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index 503ddb75..fe35d325 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,8 +23,18 @@ 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-token-keystore-1" + } + } +} + # 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,google-cloud-pypi-token" + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" } diff --git a/.repo-metadata.json b/.repo-metadata.json index 5f256c34..eb2db414 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -2,14 +2,15 @@ "name": "recommendationengine", "name_pretty": "Recommendations AI", "product_documentation": "https://cloud.google.com/recommendations-ai/", - "client_documentation": "https://googleapis.dev/python/recommendationengine/latest", + "client_documentation": "https://cloud.google.com/python/docs/reference/recommendationengine/latest", "issue_tracker": "", - "release_level": "beta", + "release_level": "preview", "language": "python", "library_type": "GAPIC_AUTO", "repo": "googleapis/python-recommendations-ai", "distribution_name": "google-cloud-recommendations-ai", "api_id": "recommendationengine.googleapis.com", "default_version": "v1beta1", - "codeowner_team": "" + "codeowner_team": "", + "api_shortname": "recommendationengine" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 99746dab..1aa5d0f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## [0.6.0](https://github.com/googleapis/python-recommendations-ai/compare/v0.5.1...v0.6.0) (2022-02-26) + + +### Features + +* add api key support ([#117](https://github.com/googleapis/python-recommendations-ai/issues/117)) ([40e4a78](https://github.com/googleapis/python-recommendations-ai/commit/40e4a783868ad748de36df77a3bca4c320bae41a)) + + +### Bug Fixes + +* resolve DuplicateCredentialArgs error when using credentials_file ([175da64](https://github.com/googleapis/python-recommendations-ai/commit/175da64cd9f6d4de184dd6cd4c304845318e9b6f)) + + +### Documentation + +* add generated snippets ([#122](https://github.com/googleapis/python-recommendations-ai/issues/122)) ([eebbeb6](https://github.com/googleapis/python-recommendations-ai/commit/eebbeb618b6dc62a1103cb6b3cbc9df65630fff3)) + ### [0.5.1](https://www.github.com/googleapis/python-recommendations-ai/compare/v0.5.0...v0.5.1) (2021-11-01) diff --git a/README.rst b/README.rst index b6e10e2e..35623fe2 100644 --- a/README.rst +++ b/README.rst @@ -15,7 +15,7 @@ Python Client for Recommendations AI .. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-recommendations-ai.svg :target: https://pypi.org/project/google-cloud-recommendations-ai/ .. _Cloud Recommendations AI API: https://cloud.google.com/recommendations-ai -.. _Client Library Documentation: https://googleapis.dev/python/recommendationengine/latest +.. _Client Library Documentation: https://cloud.google.com/python/docs/reference/recommendationengine/latest .. _Product Documentation: https://cloud.google.com/recommendations-ai Quick Start diff --git a/google/cloud/recommendationengine/__init__.py b/google/cloud/recommendationengine/__init__.py index dd05f669..05035b91 100644 --- a/google/cloud/recommendationengine/__init__.py +++ b/google/cloud/recommendationengine/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/recommendationengine_v1beta1/__init__.py b/google/cloud/recommendationengine_v1beta1/__init__.py index f29eede5..126a2331 100644 --- a/google/cloud/recommendationengine_v1beta1/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/recommendationengine_v1beta1/services/__init__.py b/google/cloud/recommendationengine_v1beta1/services/__init__.py index 4de65971..e8e1c384 100644 --- a/google/cloud/recommendationengine_v1beta1/services/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with 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 12f0071a..dcec94d4 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 b564740e..a7f67de8 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,17 +16,20 @@ from collections import OrderedDict import functools import re -from typing import Dict, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core.client_options import ClientOptions # 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.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore @@ -112,6 +115,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CatalogServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + @property def transport(self) -> CatalogServiceTransport: """Returns the transport used by the client instance. @@ -184,6 +223,31 @@ async def create_catalog_item( ) -> catalog.CatalogItem: r"""Creates a catalog item. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_create_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value_1', 'categories_value_2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.CreateCatalogItemRequest( + parent="parent_value", + catalog_item=catalog_item, + ) + + # Make the request + response = client.create_catalog_item(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.CreateCatalogItemRequest, dict]): The request object. Request message for @@ -213,7 +277,7 @@ async def create_catalog_item( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, catalog_item]) if request is not None and has_flattened_params: @@ -272,6 +336,25 @@ async def get_catalog_item( ) -> catalog.CatalogItem: r"""Gets a specific catalog item. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_get_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.GetCatalogItemRequest( + name="name_value", + ) + + # Make the request + response = client.get_catalog_item(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.GetCatalogItemRequest, dict]): The request object. Request message for GetCatalogItem @@ -296,7 +379,7 @@ async def get_catalog_item( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -354,6 +437,26 @@ async def list_catalog_items( ) -> pagers.ListCatalogItemsAsyncPager: r"""Gets a list of catalog items. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_list_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalog_items(request=request) + + # Handle the response + for response in page_result: + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsRequest, dict]): The request object. Request message for ListCatalogItems @@ -388,7 +491,7 @@ async def list_catalog_items( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, filter]) if request is not None and has_flattened_params: @@ -456,6 +559,32 @@ async def update_catalog_item( r"""Updates a catalog item. Partial updating is supported. Non-existing items will be created. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_update_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value_1', 'categories_value_2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.UpdateCatalogItemRequest( + name="name_value", + catalog_item=catalog_item, + ) + + # Make the request + response = client.update_catalog_item(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.UpdateCatalogItemRequest, dict]): The request object. Request message for @@ -495,7 +624,7 @@ async def update_catalog_item( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, catalog_item, update_mask]) if request is not None and has_flattened_params: @@ -556,6 +685,22 @@ async def delete_catalog_item( ) -> None: r"""Deletes a catalog item. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_delete_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeleteCatalogItemRequest( + name="name_value", + ) + + # Make the request + client.delete_catalog_item(request=request) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.DeleteCatalogItemRequest, dict]): The request object. Request message for @@ -574,7 +719,7 @@ async def delete_catalog_item( sent along with the request as metadata. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -639,6 +784,30 @@ async def import_catalog_items( it is possible for a subset of the items to be successfully updated. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_import_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_catalog_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsRequest, dict]): The request object. Request message for Import methods. @@ -693,7 +862,7 @@ async def import_catalog_items( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, request_id, input_config, errors_config]) if request is not None and has_flattened_params: diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py index 64f9cd01..3980674e 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/client.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,23 +14,25 @@ # limitations under the License. # from collections import OrderedDict -from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core import client_options as client_options_lib # 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 client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore @@ -240,6 +242,73 @@ def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + def __init__( self, *, @@ -290,50 +359,22 @@ def __init__( if client_options is None: client_options = client_options_lib.ClientOptions() - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool( - util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options ) - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - 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: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - 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" - ) + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, CatalogServiceTransport): # transport is a CatalogServiceTransport instance. - if credentials or client_options.credentials_file: + if credentials or client_options.credentials_file or api_key_value: raise ValueError( "When providing a transport instance, " "provide its credentials directly." @@ -345,6 +386,15 @@ def __init__( ) self._transport = transport else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, @@ -369,6 +419,31 @@ def create_catalog_item( ) -> catalog.CatalogItem: r"""Creates a catalog item. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_create_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value_1', 'categories_value_2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.CreateCatalogItemRequest( + parent="parent_value", + catalog_item=catalog_item, + ) + + # Make the request + response = client.create_catalog_item(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.CreateCatalogItemRequest, dict]): The request object. Request message for @@ -398,7 +473,7 @@ def create_catalog_item( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, catalog_item]) if request is not None and has_flattened_params: @@ -447,6 +522,25 @@ def get_catalog_item( ) -> catalog.CatalogItem: r"""Gets a specific catalog item. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_get_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.GetCatalogItemRequest( + name="name_value", + ) + + # Make the request + response = client.get_catalog_item(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.GetCatalogItemRequest, dict]): The request object. Request message for GetCatalogItem @@ -471,7 +565,7 @@ def get_catalog_item( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -519,6 +613,26 @@ def list_catalog_items( ) -> pagers.ListCatalogItemsPager: r"""Gets a list of catalog items. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_list_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalog_items(request=request) + + # Handle the response + for response in page_result: + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.ListCatalogItemsRequest, dict]): The request object. Request message for ListCatalogItems @@ -553,7 +667,7 @@ def list_catalog_items( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, filter]) if request is not None and has_flattened_params: @@ -611,6 +725,32 @@ def update_catalog_item( r"""Updates a catalog item. Partial updating is supported. Non-existing items will be created. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_update_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value_1', 'categories_value_2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.UpdateCatalogItemRequest( + name="name_value", + catalog_item=catalog_item, + ) + + # Make the request + response = client.update_catalog_item(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.UpdateCatalogItemRequest, dict]): The request object. Request message for @@ -650,7 +790,7 @@ def update_catalog_item( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, catalog_item, update_mask]) if request is not None and has_flattened_params: @@ -701,6 +841,22 @@ def delete_catalog_item( ) -> None: r"""Deletes a catalog item. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_delete_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeleteCatalogItemRequest( + name="name_value", + ) + + # Make the request + client.delete_catalog_item(request=request) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.DeleteCatalogItemRequest, dict]): The request object. Request message for @@ -719,7 +875,7 @@ def delete_catalog_item( sent along with the request as metadata. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -774,6 +930,30 @@ def import_catalog_items( it is possible for a subset of the items to be successfully updated. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_import_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_catalog_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.ImportCatalogItemsRequest, dict]): The request object. Request message for Import methods. @@ -828,7 +1008,7 @@ def import_catalog_items( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, request_id, input_config, errors_config]) if request is not None and has_flattened_params: diff --git a/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py b/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py index 490750e2..79dbe217 100644 --- a/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py +++ b/google/cloud/recommendationengine_v1beta1/services/catalog_service/pagers.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 fc02f5f3..6b59e070 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 1e783c96..65f1bd79 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -18,11 +18,11 @@ import pkg_resources 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 +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore @@ -106,7 +106,6 @@ def __init__( credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) - elif credentials is None: credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id 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 48695cda..e356ef61 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,9 +16,9 @@ import warnings 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.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,8 +165,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, @@ -239,7 +242,7 @@ def operations_client(self) -> operations_v1.OperationsClient: This property caches on the instance; repeated calls return the same client. """ - # Sanity check: Only create a new client if we do not already have one. + # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: self._operations_client = operations_v1.OperationsClient(self.grpc_channel) 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 0584001b..c8079ae8 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,9 +16,9 @@ import warnings 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.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -210,8 +210,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, @@ -241,7 +244,7 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: This property caches on the instance; repeated calls return the same client. """ - # Sanity check: Only create a new client if we do not already have one. + # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: self._operations_client = operations_v1.OperationsAsyncClient( self.grpc_channel 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 c0a8178d..caa0e09a 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 d1739e8c..b4aeee73 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,17 +16,20 @@ from collections import OrderedDict import functools import re -from typing import Dict, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core.client_options import ClientOptions # 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.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import ( pagers, @@ -125,6 +128,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return PredictionApiKeyRegistryClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + @property def transport(self) -> PredictionApiKeyRegistryTransport: """Returns the transport used by the client instance. @@ -201,6 +240,25 @@ async def create_prediction_api_key_registration( ) -> prediction_apikey_registry_service.PredictionApiKeyRegistration: r"""Register an API key for use with predict method. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_create_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CreatePredictionApiKeyRegistrationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_prediction_api_key_registration(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.CreatePredictionApiKeyRegistrationRequest, dict]): The request object. Request message for the @@ -230,7 +288,7 @@ async def create_prediction_api_key_registration( Registered Api Key. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, prediction_api_key_registration]) if request is not None and has_flattened_params: @@ -295,6 +353,27 @@ async def list_prediction_api_key_registrations( r"""List the registered apiKeys for use with predict method. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_list_prediction_api_key_registrations(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListPredictionApiKeyRegistrationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_prediction_api_key_registrations(request=request) + + # Handle the response + for response in page_result: + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest, dict]): The request object. Request message for the @@ -322,7 +401,7 @@ async def list_prediction_api_key_registrations( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -390,6 +469,22 @@ async def delete_prediction_api_key_registration( ) -> None: r"""Unregister an apiKey from using for predict method. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_delete_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeletePredictionApiKeyRegistrationRequest( + name="name_value", + ) + + # Make the request + client.delete_prediction_api_key_registration(request=request) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.DeletePredictionApiKeyRegistrationRequest, dict]): The request object. Request message for @@ -409,7 +504,7 @@ async def delete_prediction_api_key_registration( sent along with the request as metadata. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: 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 e2c68e95..8b457520 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,23 +14,25 @@ # limitations under the License. # from collections import OrderedDict -from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core import client_options as client_options_lib # 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 client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.recommendationengine_v1beta1.services.prediction_api_key_registry import ( pagers, @@ -275,6 +277,73 @@ def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + def __init__( self, *, @@ -325,50 +394,22 @@ def __init__( if client_options is None: client_options = client_options_lib.ClientOptions() - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool( - util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options ) - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - 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: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - 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" - ) + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, PredictionApiKeyRegistryTransport): # transport is a PredictionApiKeyRegistryTransport instance. - if credentials or client_options.credentials_file: + if credentials or client_options.credentials_file or api_key_value: raise ValueError( "When providing a transport instance, " "provide its credentials directly." @@ -380,6 +421,15 @@ def __init__( ) self._transport = transport else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, @@ -407,6 +457,25 @@ def create_prediction_api_key_registration( ) -> prediction_apikey_registry_service.PredictionApiKeyRegistration: r"""Register an API key for use with predict method. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_create_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CreatePredictionApiKeyRegistrationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_prediction_api_key_registration(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.CreatePredictionApiKeyRegistrationRequest, dict]): The request object. Request message for the @@ -436,7 +505,7 @@ def create_prediction_api_key_registration( Registered Api Key. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, prediction_api_key_registration]) if request is not None and has_flattened_params: @@ -498,6 +567,27 @@ def list_prediction_api_key_registrations( r"""List the registered apiKeys for use with predict method. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_list_prediction_api_key_registrations(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListPredictionApiKeyRegistrationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_prediction_api_key_registrations(request=request) + + # Handle the response + for response in page_result: + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.ListPredictionApiKeyRegistrationsRequest, dict]): The request object. Request message for the @@ -525,7 +615,7 @@ def list_prediction_api_key_registrations( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -588,6 +678,22 @@ def delete_prediction_api_key_registration( ) -> None: r"""Unregister an apiKey from using for predict method. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_delete_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeletePredictionApiKeyRegistrationRequest( + name="name_value", + ) + + # Make the request + client.delete_prediction_api_key_registration(request=request) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.DeletePredictionApiKeyRegistrationRequest, dict]): The request object. Request message for @@ -607,7 +713,7 @@ def delete_prediction_api_key_registration( sent along with the request as metadata. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: 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 cb502a10..c658450f 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 5f9a2a13..4662b6db 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 d4e22f5f..24b6a10f 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -18,10 +18,10 @@ import pkg_resources 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 +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore @@ -104,7 +104,6 @@ def __init__( credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) - elif credentials is None: credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id 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 9f1e15e4..8ae1d305 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ import warnings 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.api_core import grpc_helpers +from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -166,8 +166,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, 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 af1197fa..5eb49e8f 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ import warnings 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 gapic_v1 +from google.api_core import grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -211,8 +211,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py index 12491bb1..d5ecd0dd 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 0ddf5480..07a39569 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,17 +16,20 @@ from collections import OrderedDict import functools import re -from typing import Dict, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core.client_options import ClientOptions # 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.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers from google.cloud.recommendationengine_v1beta1.types import prediction_service @@ -104,6 +107,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return PredictionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + @property def transport(self) -> PredictionServiceTransport: """Returns the transport used by the client instance. @@ -180,6 +219,32 @@ async def predict( service. `Learn more `__. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_predict(): + # Create a client + client = recommendationengine_v1beta1.PredictionServiceClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.PredictRequest( + name="name_value", + user_event=user_event, + ) + + # Make the request + page_result = client.predict(request=request) + + # Handle the response + for response in page_result: + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.PredictRequest, dict]): The request object. Request message for Predict method. @@ -252,7 +317,7 @@ async def predict( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, user_event]) if request is not None and has_flattened_params: diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py index 978ca97f..bb41a348 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/client.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,23 +14,25 @@ # limitations under the License. # from collections import OrderedDict -from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core import client_options as client_options_lib # 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 client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.recommendationengine_v1beta1.services.prediction_service import pagers from google.cloud.recommendationengine_v1beta1.types import prediction_service @@ -241,6 +243,73 @@ def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + def __init__( self, *, @@ -291,50 +360,22 @@ def __init__( if client_options is None: client_options = client_options_lib.ClientOptions() - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool( - util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options ) - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - 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: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - 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" - ) + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, PredictionServiceTransport): # transport is a PredictionServiceTransport instance. - if credentials or client_options.credentials_file: + if credentials or client_options.credentials_file or api_key_value: raise ValueError( "When providing a transport instance, " "provide its credentials directly." @@ -346,6 +387,15 @@ def __init__( ) self._transport = transport else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, @@ -374,6 +424,32 @@ def predict( service. `Learn more `__. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_predict(): + # Create a client + client = recommendationengine_v1beta1.PredictionServiceClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.PredictRequest( + name="name_value", + user_event=user_event, + ) + + # Make the request + page_result = client.predict(request=request) + + # Handle the response + for response in page_result: + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.PredictRequest, dict]): The request object. Request message for Predict method. @@ -446,7 +522,7 @@ def predict( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, user_event]) if request is not None and has_flattened_params: diff --git a/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py b/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py index 73946202..9d4d53ed 100644 --- a/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py +++ b/google/cloud/recommendationengine_v1beta1/services/prediction_service/pagers.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 86d2e8a7..3b81984d 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 68d62ef6..6eb54c95 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -18,10 +18,10 @@ import pkg_resources 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 +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore @@ -101,7 +101,6 @@ def __init__( credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) - elif credentials is None: credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id 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 3f6fb665..e4db259c 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ import warnings 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.api_core import grpc_helpers +from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -158,8 +158,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, 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 48d0d1f5..4502a535 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ import warnings 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 gapic_v1 +from google.api_core import grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -203,8 +203,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, 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 5d067fc3..f7ce3d76 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 d47cfb30..55dbfa7f 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,17 +16,20 @@ from collections import OrderedDict import functools import re -from typing import Dict, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core.client_options import ClientOptions # 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.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.api import httpbody_pb2 # type: ignore from google.api_core import operation # type: ignore @@ -113,6 +116,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + @property def transport(self) -> UserEventServiceTransport: """Returns the transport used by the client instance. @@ -185,6 +224,30 @@ async def write_user_event( ) -> gcr_user_event.UserEvent: r"""Writes a single user event. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_write_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.WriteUserEventRequest, dict]): The request object. Request message for WriteUserEvent @@ -216,7 +279,7 @@ async def write_user_event( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, user_event]) if request is not None and has_flattened_params: @@ -283,6 +346,27 @@ async def collect_user_event( JavaScript pixel. Users should not call this method directly. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_collect_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.CollectUserEventRequest, dict]): The request object. Request message for CollectUserEvent @@ -302,8 +386,8 @@ async def collect_user_event( on the ``request`` instance; if ``request`` is provided, this should not be set. uri (:class:`str`): - Optional. The url including cgi- - arameters but excluding the hash + Optional. The url including + cgi-parameters but excluding the hash fragment. The URL must be truncated to 1.5K bytes to conservatively be under the 2K bytes. This is often more useful @@ -381,7 +465,7 @@ async def collect_user_event( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, user_event, uri, ets]) if request is not None and has_flattened_params: @@ -446,6 +530,27 @@ async def list_user_events( r"""Gets a list of user events within a time range, with potential filtering. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_list_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListUserEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_events(request=request) + + # Handle the response + for response in page_result: + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.ListUserEventsRequest, dict]): The request object. Request message for ListUserEvents @@ -514,7 +619,7 @@ async def list_user_events( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, filter]) if request is not None and has_flattened_params: @@ -585,6 +690,31 @@ async def purge_user_events( or days to complete. To test a filter, use the list command first. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_purge_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.PurgeUserEventsRequest, dict]): The request object. Request message for PurgeUserEvents @@ -647,7 +777,7 @@ async def purge_user_events( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, filter, force]) if request is not None and has_flattened_params: @@ -725,6 +855,30 @@ async def import_user_events( successfully inserted. Operation.metadata is of type ImportMetadata. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_import_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.ImportUserEventsRequest, dict]): The request object. Request message for the @@ -780,7 +934,7 @@ async def import_user_events( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, request_id, input_config, errors_config]) if request is not None and has_flattened_params: 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 ba3a80a5..4cb8a18f 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,23 +14,25 @@ # limitations under the License. # from collections import OrderedDict -from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core import client_options as client_options_lib # 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 client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.api import httpbody_pb2 # type: ignore from google.api_core import operation # type: ignore @@ -247,6 +249,73 @@ def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + def __init__( self, *, @@ -297,50 +366,22 @@ def __init__( if client_options is None: client_options = client_options_lib.ClientOptions() - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool( - util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options ) - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - 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: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - 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" - ) + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, UserEventServiceTransport): # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file: + if credentials or client_options.credentials_file or api_key_value: raise ValueError( "When providing a transport instance, " "provide its credentials directly." @@ -352,6 +393,15 @@ def __init__( ) self._transport = transport else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, @@ -376,6 +426,30 @@ def write_user_event( ) -> gcr_user_event.UserEvent: r"""Writes a single user event. + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_write_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.WriteUserEventRequest, dict]): The request object. Request message for WriteUserEvent @@ -407,7 +481,7 @@ def write_user_event( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, user_event]) if request is not None and has_flattened_params: @@ -464,6 +538,27 @@ def collect_user_event( JavaScript pixel. Users should not call this method directly. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_collect_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.CollectUserEventRequest, dict]): The request object. Request message for CollectUserEvent @@ -483,8 +578,8 @@ def collect_user_event( on the ``request`` instance; if ``request`` is provided, this should not be set. uri (str): - Optional. The url including cgi- - arameters but excluding the hash + Optional. The url including + cgi-parameters but excluding the hash fragment. The URL must be truncated to 1.5K bytes to conservatively be under the 2K bytes. This is often more useful @@ -562,7 +657,7 @@ def collect_user_event( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, user_event, uri, ets]) if request is not None and has_flattened_params: @@ -617,6 +712,27 @@ def list_user_events( r"""Gets a list of user events within a time range, with potential filtering. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_list_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListUserEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_events(request=request) + + # Handle the response + for response in page_result: + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.ListUserEventsRequest, dict]): The request object. Request message for ListUserEvents @@ -685,7 +801,7 @@ def list_user_events( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, filter]) if request is not None and has_flattened_params: @@ -746,6 +862,31 @@ def purge_user_events( or days to complete. To test a filter, use the list command first. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_purge_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.PurgeUserEventsRequest, dict]): The request object. Request message for PurgeUserEvents @@ -808,7 +949,7 @@ def purge_user_events( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, filter, force]) if request is not None and has_flattened_params: @@ -876,6 +1017,30 @@ def import_user_events( successfully inserted. Operation.metadata is of type ImportMetadata. + + .. code-block:: python + + from google.cloud import recommendationengine_v1beta1 + + def sample_import_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.recommendationengine_v1beta1.types.ImportUserEventsRequest, dict]): The request object. Request message for the @@ -931,7 +1096,7 @@ def import_user_events( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, request_id, input_config, errors_config]) if request is not None and has_flattened_params: 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 a176abd7..7cd2bf65 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 4c90ca7e..a64577a7 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 fa852f7a..ccfb7cac 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -18,11 +18,11 @@ import pkg_resources 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 +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore @@ -106,7 +106,6 @@ def __init__( credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) - elif credentials is None: credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id 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 05e9f4a8..a55c231c 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,9 +16,9 @@ import warnings 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.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -165,8 +165,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, @@ -239,7 +242,7 @@ def operations_client(self) -> operations_v1.OperationsClient: This property caches on the instance; repeated calls return the same client. """ - # Sanity check: Only create a new client if we do not already have one. + # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: self._operations_client = operations_v1.OperationsClient(self.grpc_channel) 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 379215fd..ea022ea3 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,9 +16,9 @@ import warnings 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.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -210,8 +210,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, @@ -241,7 +244,7 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: This property caches on the instance; repeated calls return the same client. """ - # Sanity check: Only create a new client if we do not already have one. + # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: self._operations_client = operations_v1.OperationsAsyncClient( self.grpc_channel diff --git a/google/cloud/recommendationengine_v1beta1/types/__init__.py b/google/cloud/recommendationengine_v1beta1/types/__init__.py index 895d1c28..355c7890 100644 --- a/google/cloud/recommendationengine_v1beta1/types/__init__.py +++ b/google/cloud/recommendationengine_v1beta1/types/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/recommendationengine_v1beta1/types/catalog.py b/google/cloud/recommendationengine_v1beta1/types/catalog.py index 404afa39..c4fa5f31 100644 --- a/google/cloud/recommendationengine_v1beta1/types/catalog.py +++ b/google/cloud/recommendationengine_v1beta1/types/catalog.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -91,6 +91,7 @@ class CatalogItem(proto.Message): product_metadata (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem): Optional. Metadata specific to retail products. + This field is a member of `oneof`_ ``recommendation_type``. """ @@ -140,9 +141,11 @@ class ProductCatalogItem(proto.Message): Attributes: exact_price (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.ExactPrice): Optional. The exact product price. + This field is a member of `oneof`_ ``price``. price_range (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.PriceRange): Optional. The product price range. + This field is a member of `oneof`_ ``price``. costs (Sequence[google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.CostsEntry]): Optional. A map to pass the costs associated with the @@ -157,8 +160,8 @@ class ProductCatalogItem(proto.Message): sum(costs) currency_code (str): Optional. Only required if the price is set. - Currency code for price/costs. Use three- - character ISO-4217 code. + Currency code for price/costs. Use + three-character ISO-4217 code. stock_state (google.cloud.recommendationengine_v1beta1.types.ProductCatalogItem.StockState): Optional. Online stock state of the catalog item. Default is ``IN_STOCK``. diff --git a/google/cloud/recommendationengine_v1beta1/types/catalog_service.py b/google/cloud/recommendationengine_v1beta1/types/catalog_service.py index 1e783e55..96b734d4 100644 --- a/google/cloud/recommendationengine_v1beta1/types/catalog_service.py +++ b/google/cloud/recommendationengine_v1beta1/types/catalog_service.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/recommendationengine_v1beta1/types/common.py b/google/cloud/recommendationengine_v1beta1/types/common.py index 2adbf290..1f43577c 100644 --- a/google/cloud/recommendationengine_v1beta1/types/common.py +++ b/google/cloud/recommendationengine_v1beta1/types/common.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/recommendationengine_v1beta1/types/import_.py b/google/cloud/recommendationengine_v1beta1/types/import_.py index c095a731..e0d798d9 100644 --- a/google/cloud/recommendationengine_v1beta1/types/import_.py +++ b/google/cloud/recommendationengine_v1beta1/types/import_.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -100,6 +100,7 @@ class ImportErrorsConfig(proto.Message): empty, existing Cloud Storage bucket. Import errors will be written to a file in this bucket, one per line, as a JSON-encoded ``google.rpc.Status`` message. + This field is a member of `oneof`_ ``destination``. """ @@ -178,14 +179,17 @@ class InputConfig(proto.Message): catalog_inline_source (google.cloud.recommendationengine_v1beta1.types.CatalogInlineSource): The Inline source for the input content for Catalog items. + This field is a member of `oneof`_ ``source``. gcs_source (google.cloud.recommendationengine_v1beta1.types.GcsSource): Google Cloud Storage location for the input content. + This field is a member of `oneof`_ ``source``. user_event_inline_source (google.cloud.recommendationengine_v1beta1.types.UserEventInlineSource): The Inline source for the input content for UserEvents. + This field is a member of `oneof`_ ``source``. """ 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 1acea0a9..003edc71 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/recommendationengine_v1beta1/types/prediction_service.py b/google/cloud/recommendationengine_v1beta1/types/prediction_service.py index 5ffa0f11..ae51ef75 100644 --- a/google/cloud/recommendationengine_v1beta1/types/prediction_service.py +++ b/google/cloud/recommendationengine_v1beta1/types/prediction_service.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py b/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py index 29a95c74..167f688d 100644 --- a/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py +++ b/google/cloud/recommendationengine_v1beta1/types/recommendationengine_resources.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/recommendationengine_v1beta1/types/user_event.py b/google/cloud/recommendationengine_v1beta1/types/user_event.py index bb913090..be5331ad 100644 --- a/google/cloud/recommendationengine_v1beta1/types/user_event.py +++ b/google/cloud/recommendationengine_v1beta1/types/user_event.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/google/cloud/recommendationengine_v1beta1/types/user_event_service.py b/google/cloud/recommendationengine_v1beta1/types/user_event_service.py index 05b14d11..c23ea78b 100644 --- a/google/cloud/recommendationengine_v1beta1/types/user_event_service.py +++ b/google/cloud/recommendationengine_v1beta1/types/user_event_service.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/noxfile.py b/noxfile.py index f041f1f5..2a2001c4 100644 --- a/noxfile.py +++ b/noxfile.py @@ -175,7 +175,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=98") + session.run("coverage", "report", "--show-missing", "--fail-under=100") session.run("coverage", "erase") diff --git a/owlbot.py b/owlbot.py index 4b6c5a97..21a42fe9 100644 --- a/owlbot.py +++ b/owlbot.py @@ -93,7 +93,7 @@ # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=98, microgenerator=True) +templated_files = common.py_library(cov_level=100, microgenerator=True) s.move( templated_files, excludes=[".coveragerc"] @@ -101,4 +101,4 @@ python.py_samples(skip_readmes=True) -s.shell.run(["nox", "-s", "blacken"], hide_output=False) \ No newline at end of file +s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_async.py new file mode 100644 index 00000000..983ce382 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_create_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value_1', 'categories_value_2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.CreateCatalogItemRequest( + parent="parent_value", + catalog_item=catalog_item, + ) + + # Make the request + response = await client.create_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_sync.py new file mode 100644 index 00000000..19fced84 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_create_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value_1', 'categories_value_2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.CreateCatalogItemRequest( + parent="parent_value", + catalog_item=catalog_item, + ) + + # Make the request + response = client.create_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_async.py new file mode 100644 index 00000000..1b9e12c4 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_delete_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeleteCatalogItemRequest( + name="name_value", + ) + + # Make the request + await client.delete_catalog_item(request=request) + + +# [END recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_sync.py new file mode 100644 index 00000000..5457ec85 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_delete_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeleteCatalogItemRequest( + name="name_value", + ) + + # Make the request + client.delete_catalog_item(request=request) + + +# [END recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_async.py new file mode 100644 index 00000000..f3bafb32 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_get_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.GetCatalogItemRequest( + name="name_value", + ) + + # Make the request + response = await client.get_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_sync.py new file mode 100644 index 00000000..1a9dda6a --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_get_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.GetCatalogItemRequest( + name="name_value", + ) + + # Make the request + response = client.get_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_async.py new file mode 100644 index 00000000..18293d52 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCatalogItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_import_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_catalog_items(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_sync.py new file mode 100644 index 00000000..79f5a34e --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCatalogItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_import_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_catalog_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_async.py new file mode 100644 index 00000000..abcb06ec --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_list_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalog_items(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_sync.py new file mode 100644 index 00000000..dbf9fe78 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCatalogItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_list_catalog_items(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListCatalogItemsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_catalog_items(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_async.py new file mode 100644 index 00000000..9217f6a5 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_update_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceAsyncClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value_1', 'categories_value_2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.UpdateCatalogItemRequest( + name="name_value", + catalog_item=catalog_item, + ) + + # Make the request + response = await client.update_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_sync.py new file mode 100644 index 00000000..36ac1a7d --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCatalogItem +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_update_catalog_item(): + # Create a client + client = recommendationengine_v1beta1.CatalogServiceClient() + + # Initialize request argument(s) + catalog_item = recommendationengine_v1beta1.CatalogItem() + catalog_item.id = "id_value" + catalog_item.category_hierarchies.categories = ['categories_value_1', 'categories_value_2'] + catalog_item.title = "title_value" + + request = recommendationengine_v1beta1.UpdateCatalogItemRequest( + name="name_value", + catalog_item=catalog_item, + ) + + # Make the request + response = client.update_catalog_item(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_async.py new file mode 100644 index 00000000..7df31e02 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreatePredictionApiKeyRegistration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_create_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CreatePredictionApiKeyRegistrationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_prediction_api_key_registration(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_sync.py new file mode 100644 index 00000000..46f66db3 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreatePredictionApiKeyRegistration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_create_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CreatePredictionApiKeyRegistrationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_prediction_api_key_registration(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_async.py new file mode 100644 index 00000000..3613e294 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_async.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeletePredictionApiKeyRegistration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_delete_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeletePredictionApiKeyRegistrationRequest( + name="name_value", + ) + + # Make the request + await client.delete_prediction_api_key_registration(request=request) + + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_sync.py new file mode 100644 index 00000000..ee042845 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_sync.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeletePredictionApiKeyRegistration +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_delete_prediction_api_key_registration(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.DeletePredictionApiKeyRegistrationRequest( + name="name_value", + ) + + # Make the request + client.delete_prediction_api_key_registration(request=request) + + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_async.py new file mode 100644 index 00000000..033668f5 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPredictionApiKeyRegistrations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_list_prediction_api_key_registrations(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListPredictionApiKeyRegistrationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_prediction_api_key_registrations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_sync.py new file mode 100644 index 00000000..da57e548 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPredictionApiKeyRegistrations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_list_prediction_api_key_registrations(): + # Create a client + client = recommendationengine_v1beta1.PredictionApiKeyRegistryClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListPredictionApiKeyRegistrationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_prediction_api_key_registrations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_async.py new file mode 100644 index 00000000..e7e6e709 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionService_Predict_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_predict(): + # Create a client + client = recommendationengine_v1beta1.PredictionServiceAsyncClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.PredictRequest( + name="name_value", + user_event=user_event, + ) + + # Make the request + page_result = client.predict(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionService_Predict_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_sync.py new file mode 100644 index 00000000..3599e87b --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_prediction_service_predict_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Predict +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_PredictionService_Predict_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_predict(): + # Create a client + client = recommendationengine_v1beta1.PredictionServiceClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.PredictRequest( + name="name_value", + user_event=user_event, + ) + + # Make the request + page_result = client.predict(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_PredictionService_Predict_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 00000000..5864d0c7 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_collect_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 00000000..79e3a7cf --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_collect_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_async.py new file mode 100644 index 00000000..74ce6bba --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_import_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 00000000..9fed9ad4 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_import_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ImportUserEventsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_async.py new file mode 100644 index 00000000..3f069746 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_list_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListUserEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_sync.py new file mode 100644 index 00000000..d5fbaae5 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_list_user_events_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_list_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.ListUserEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_user_events(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 00000000..704776e0 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_purge_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 00000000..ef7cf9d2 --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_purge_user_events(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + request = recommendationengine_v1beta1.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_sync] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_async.py b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_async.py new file mode 100644 index 00000000..aad5174f --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_async] +from google.cloud import recommendationengine_v1beta1 + + +async def sample_write_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_async] diff --git a/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_sync.py b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 00000000..cee1ebab --- /dev/null +++ b/samples/generated_samples/recommendationengine_v1beta1_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-recommendations-ai + + +# [START recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_sync] +from google.cloud import recommendationengine_v1beta1 + + +def sample_write_user_event(): + # Create a client + client = recommendationengine_v1beta1.UserEventServiceClient() + + # Initialize request argument(s) + user_event = recommendationengine_v1beta1.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_info.visitor_id = "visitor_id_value" + + request = recommendationengine_v1beta1.WriteUserEventRequest( + parent="parent_value", + user_event=user_event, + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_sync] diff --git a/samples/generated_samples/snippet_metadata_recommendationengine_v1beta1.json b/samples/generated_samples/snippet_metadata_recommendationengine_v1beta1.json new file mode 100644 index 00000000..d911073b --- /dev/null +++ b/samples/generated_samples/snippet_metadata_recommendationengine_v1beta1.json @@ -0,0 +1,1331 @@ +{ + "snippets": [ + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "CreateCatalogItem" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_async.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "CreateCatalogItem" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_create_catalog_item_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_CreateCatalogItem_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "DeleteCatalogItem" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_async.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "DeleteCatalogItem" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_delete_catalog_item_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_DeleteCatalogItem_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "GetCatalogItem" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_async.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "GetCatalogItem" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_get_catalog_item_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_GetCatalogItem_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "ImportCatalogItems" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_async.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "ImportCatalogItems" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_import_catalog_items_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_ImportCatalogItems_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "ListCatalogItems" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_async.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "ListCatalogItems" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_list_catalog_items_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_ListCatalogItems_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalogItem" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_async.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "CatalogService" + }, + "shortName": "UpdateCatalogItem" + } + }, + "file": "recommendationengine_v1beta1_generated_catalog_service_update_catalog_item_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_CatalogService_UpdateCatalogItem_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "CreatePredictionApiKeyRegistration" + } + }, + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_async.py", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "CreatePredictionApiKeyRegistration" + } + }, + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_create_prediction_api_key_registration_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_CreatePredictionApiKeyRegistration_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "DeletePredictionApiKeyRegistration" + } + }, + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_async.py", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_async", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "DeletePredictionApiKeyRegistration" + } + }, + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_delete_prediction_api_key_registration_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_DeletePredictionApiKeyRegistration_sync", + "segments": [ + { + "end": 42, + "start": 27, + "type": "FULL" + }, + { + "end": 42, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 43, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "ListPredictionApiKeyRegistrations" + } + }, + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_async.py", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "PredictionApiKeyRegistry" + }, + "shortName": "ListPredictionApiKeyRegistrations" + } + }, + "file": "recommendationengine_v1beta1_generated_prediction_api_key_registry_list_prediction_api_key_registrations_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_PredictionApiKeyRegistry_ListPredictionApiKeyRegistrations_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "PredictionService" + }, + "shortName": "Predict" + } + }, + "file": "recommendationengine_v1beta1_generated_prediction_service_predict_async.py", + "regionTag": "recommendationengine_v1beta1_generated_PredictionService_Predict_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "PredictionService" + }, + "shortName": "Predict" + } + }, + "file": "recommendationengine_v1beta1_generated_prediction_service_predict_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_PredictionService_Predict_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + } + }, + "file": "recommendationengine_v1beta1_generated_user_event_service_collect_user_event_async.py", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + } + }, + "file": "recommendationengine_v1beta1_generated_user_event_service_collect_user_event_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_CollectUserEvent_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + } + }, + "file": "recommendationengine_v1beta1_generated_user_event_service_import_user_events_async.py", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + } + }, + "file": "recommendationengine_v1beta1_generated_user_event_service_import_user_events_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_ImportUserEvents_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "UserEventService" + }, + "shortName": "ListUserEvents" + } + }, + "file": "recommendationengine_v1beta1_generated_user_event_service_list_user_events_async.py", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "UserEventService" + }, + "shortName": "ListUserEvents" + } + }, + "file": "recommendationengine_v1beta1_generated_user_event_service_list_user_events_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_ListUserEvents_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + } + }, + "file": "recommendationengine_v1beta1_generated_user_event_service_purge_user_events_async.py", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + } + }, + "file": "recommendationengine_v1beta1_generated_user_event_service_purge_user_events_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_PurgeUserEvents_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + } + }, + "file": "recommendationengine_v1beta1_generated_user_event_service_write_user_event_async.py", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + } + }, + "file": "recommendationengine_v1beta1_generated_user_event_service_write_user_event_sync.py", + "regionTag": "recommendationengine_v1beta1_generated_UserEventService_WriteUserEvent_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 43, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 46, + "start": 44, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "start": 47, + "type": "RESPONSE_HANDLING" + } + ] + } + ] +} diff --git a/scripts/fixup_recommendationengine_v1beta1_keywords.py b/scripts/fixup_recommendationengine_v1beta1_keywords.py index 6bb5115d..721daf79 100644 --- a/scripts/fixup_recommendationengine_v1beta1_keywords.py +++ b/scripts/fixup_recommendationengine_v1beta1_keywords.py @@ -1,6 +1,6 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/setup.py b/setup.py index a2a2ba45..f459c578 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ import os import setuptools # type: ignore -version = "0.5.1" +version = "0.6.0" package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/tests/__init__.py b/tests/__init__.py index 4de65971..e8e1c384 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py index 4de65971..e8e1c384 100644 --- a/tests/unit/__init__.py +++ b/tests/unit/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py index 4de65971..e8e1c384 100644 --- a/tests/unit/gapic/__init__.py +++ b/tests/unit/gapic/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/tests/unit/gapic/recommendationengine_v1beta1/__init__.py b/tests/unit/gapic/recommendationengine_v1beta1/__init__.py index 4de65971..e8e1c384 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/__init__.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/__init__.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with 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 8c9f0bd0..c803293a 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/test_catalog_service.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -29,6 +29,7 @@ from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async +from google.api_core import operation from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 from google.api_core import path_template @@ -262,20 +263,20 @@ def test_catalog_service_client_client_options( # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): - client = client_class() + client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): - client = client_class() + client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -334,7 +335,7 @@ def test_catalog_service_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None @@ -411,6 +412,87 @@ def test_catalog_service_client_mtls_env_auto( ) +@pytest.mark.parametrize( + "client_class", [CatalogServiceClient, CatalogServiceAsyncClient] +) +@mock.patch.object( + CatalogServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CatalogServiceClient), +) +@mock.patch.object( + CatalogServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CatalogServiceAsyncClient), +) +def test_catalog_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + @pytest.mark.parametrize( "client_class,transport_class,transport_name", [ @@ -429,7 +511,7 @@ def test_catalog_service_client_client_options_scopes( options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -443,24 +525,31 @@ def test_catalog_service_client_client_options_scopes( @pytest.mark.parametrize( - "client_class,transport_class,transport_name", + "client_class,transport_class,transport_name,grpc_helpers", [ - (CatalogServiceClient, transports.CatalogServiceGrpcTransport, "grpc"), + ( + CatalogServiceClient, + transports.CatalogServiceGrpcTransport, + "grpc", + grpc_helpers, + ), ( CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport, "grpc_asyncio", + grpc_helpers_async, ), ], ) def test_catalog_service_client_client_options_credentials_file( - client_class, transport_class, transport_name + client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -493,9 +582,76 @@ def test_catalog_service_client_client_options_from_dict(): ) -def test_create_catalog_item( - transport: str = "grpc", request_type=catalog_service.CreateCatalogItemRequest +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + CatalogServiceClient, + transports.CatalogServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CatalogServiceAsyncClient, + transports.CatalogServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_catalog_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers ): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "recommendationengine.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="recommendationengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", [catalog_service.CreateCatalogItemRequest, dict,] +) +def test_create_catalog_item(request_type, transport: str = "grpc"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -537,10 +693,6 @@ def test_create_catalog_item( assert response.item_group_id == "item_group_id_value" -def test_create_catalog_item_from_dict(): - test_create_catalog_item(request_type=dict) - - 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. @@ -682,8 +834,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") + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].catalog_item + mock_val = catalog.CatalogItem(id="id_value") + assert arg == mock_val def test_create_catalog_item_flattened_error(): @@ -723,8 +879,12 @@ 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") + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].catalog_item + mock_val = catalog.CatalogItem(id="id_value") + assert arg == mock_val @pytest.mark.asyncio @@ -743,9 +903,8 @@ async def test_create_catalog_item_flattened_error_async(): ) -def test_get_catalog_item( - transport: str = "grpc", request_type=catalog_service.GetCatalogItemRequest -): +@pytest.mark.parametrize("request_type", [catalog_service.GetCatalogItemRequest, dict,]) +def test_get_catalog_item(request_type, transport: str = "grpc"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -785,10 +944,6 @@ def test_get_catalog_item( assert response.item_group_id == "item_group_id_value" -def test_get_catalog_item_from_dict(): - test_get_catalog_item(request_type=dict) - - 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. @@ -917,7 +1072,9 @@ 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" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val def test_get_catalog_item_flattened_error(): @@ -951,7 +1108,9 @@ 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" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val @pytest.mark.asyncio @@ -968,9 +1127,10 @@ async def test_get_catalog_item_flattened_error_async(): ) -def test_list_catalog_items( - transport: str = "grpc", request_type=catalog_service.ListCatalogItemsRequest -): +@pytest.mark.parametrize( + "request_type", [catalog_service.ListCatalogItemsRequest, dict,] +) +def test_list_catalog_items(request_type, transport: str = "grpc"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -999,10 +1159,6 @@ def test_list_catalog_items( assert response.next_page_token == "next_page_token_value" -def test_list_catalog_items_from_dict(): - test_list_catalog_items(request_type=dict) - - 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. @@ -1136,8 +1292,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" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val def test_list_catalog_items_flattened_error(): @@ -1179,8 +1339,12 @@ 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" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val @pytest.mark.asyncio @@ -1199,8 +1363,10 @@ async def test_list_catalog_items_flattened_error_async(): ) -def test_list_catalog_items_pager(): - client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials,) +def test_list_catalog_items_pager(transport_name: str = "grpc"): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1241,8 +1407,10 @@ def test_list_catalog_items_pager(): assert all(isinstance(i, catalog.CatalogItem) for i in results) -def test_list_catalog_items_pages(): - client = CatalogServiceClient(credentials=ga_credentials.AnonymousCredentials,) +def test_list_catalog_items_pages(transport_name: str = "grpc"): + client = CatalogServiceClient( + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1353,9 +1521,10 @@ async def test_list_catalog_items_async_pages(): assert page_.raw_page.next_page_token == token -def test_update_catalog_item( - transport: str = "grpc", request_type=catalog_service.UpdateCatalogItemRequest -): +@pytest.mark.parametrize( + "request_type", [catalog_service.UpdateCatalogItemRequest, dict,] +) +def test_update_catalog_item(request_type, transport: str = "grpc"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1397,10 +1566,6 @@ def test_update_catalog_item( assert response.item_group_id == "item_group_id_value" -def test_update_catalog_item_from_dict(): - test_update_catalog_item(request_type=dict) - - 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. @@ -1544,9 +1709,15 @@ def test_update_catalog_item_flattened(): # 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_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].catalog_item + mock_val = catalog.CatalogItem(id="id_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val def test_update_catalog_item_flattened_error(): @@ -1589,9 +1760,15 @@ async def test_update_catalog_item_flattened_async(): # 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_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].catalog_item + mock_val = catalog.CatalogItem(id="id_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val @pytest.mark.asyncio @@ -1611,9 +1788,10 @@ async def test_update_catalog_item_flattened_error_async(): ) -def test_delete_catalog_item( - transport: str = "grpc", request_type=catalog_service.DeleteCatalogItemRequest -): +@pytest.mark.parametrize( + "request_type", [catalog_service.DeleteCatalogItemRequest, dict,] +) +def test_delete_catalog_item(request_type, transport: str = "grpc"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1639,10 +1817,6 @@ def test_delete_catalog_item( assert response is None -def test_delete_catalog_item_from_dict(): - test_delete_catalog_item(request_type=dict) - - 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. @@ -1767,7 +1941,9 @@ 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" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val def test_delete_catalog_item_flattened_error(): @@ -1803,7 +1979,9 @@ 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" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val @pytest.mark.asyncio @@ -1820,9 +1998,8 @@ async def test_delete_catalog_item_flattened_error_async(): ) -def test_import_catalog_items( - transport: str = "grpc", request_type=import_.ImportCatalogItemsRequest -): +@pytest.mark.parametrize("request_type", [import_.ImportCatalogItemsRequest, dict,]) +def test_import_catalog_items(request_type, transport: str = "grpc"): client = CatalogServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1848,10 +2025,6 @@ def test_import_catalog_items( assert isinstance(response, future.Future) -def test_import_catalog_items_from_dict(): - test_import_catalog_items(request_type=dict) - - 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. @@ -1988,16 +2161,22 @@ 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( + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].request_id + mock_val = "request_id_value" + assert arg == mock_val + arg = args[0].input_config + mock_val = import_.InputConfig( catalog_inline_source=import_.CatalogInlineSource( catalog_items=[catalog.CatalogItem(id="id_value")] ) ) - assert args[0].errors_config == import_.ImportErrorsConfig( - gcs_prefix="gcs_prefix_value" - ) + assert arg == mock_val + arg = args[0].errors_config + mock_val = import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value") + assert arg == mock_val def test_import_catalog_items_flattened_error(): @@ -2052,16 +2231,22 @@ 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( + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].request_id + mock_val = "request_id_value" + assert arg == mock_val + arg = args[0].input_config + mock_val = import_.InputConfig( catalog_inline_source=import_.CatalogInlineSource( catalog_items=[catalog.CatalogItem(id="id_value")] ) ) - assert args[0].errors_config == import_.ImportErrorsConfig( - gcs_prefix="gcs_prefix_value" - ) + assert arg == mock_val + arg = args[0].errors_config + mock_val = import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value") + assert arg == mock_val @pytest.mark.asyncio @@ -2106,6 +2291,23 @@ def test_credentials_transport_error(): transport=transport, ) + # It is an error to provide an api_key and a transport instance. + transport = transports.CatalogServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient(client_options=options, transport=transport,) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CatalogServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + # It is an error to provide scopes and a transport instance. transport = transports.CatalogServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2541,7 +2743,7 @@ def test_parse_catalog_path(): def test_common_billing_account_path(): - billing_account = "squid" + billing_account = "whelk" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2551,7 +2753,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "clam", + "billing_account": "octopus", } path = CatalogServiceClient.common_billing_account_path(**expected) @@ -2561,7 +2763,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "whelk" + folder = "oyster" expected = "folders/{folder}".format(folder=folder,) actual = CatalogServiceClient.common_folder_path(folder) assert expected == actual @@ -2569,7 +2771,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "octopus", + "folder": "nudibranch", } path = CatalogServiceClient.common_folder_path(**expected) @@ -2579,7 +2781,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "oyster" + organization = "cuttlefish" expected = "organizations/{organization}".format(organization=organization,) actual = CatalogServiceClient.common_organization_path(organization) assert expected == actual @@ -2587,7 +2789,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nudibranch", + "organization": "mussel", } path = CatalogServiceClient.common_organization_path(**expected) @@ -2597,7 +2799,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "cuttlefish" + project = "winkle" expected = "projects/{project}".format(project=project,) actual = CatalogServiceClient.common_project_path(project) assert expected == actual @@ -2605,7 +2807,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "mussel", + "project": "nautilus", } path = CatalogServiceClient.common_project_path(**expected) @@ -2615,8 +2817,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "winkle" - location = "nautilus" + project = "scallop" + location = "abalone" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2626,8 +2828,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "scallop", - "location": "abalone", + "project": "squid", + "location": "clam", } path = CatalogServiceClient.common_location_path(**expected) @@ -2636,7 +2838,7 @@ def test_parse_common_location_path(): assert expected == actual -def test_client_withDEFAULT_CLIENT_INFO(): +def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( @@ -2701,3 +2903,33 @@ def test_client_ctx(): with client: pass close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (CatalogServiceClient, transports.CatalogServiceGrpcTransport), + (CatalogServiceAsyncClient, transports.CatalogServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py b/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_api_key_registry.py index 3d0574cc..308eb44c 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -267,20 +267,20 @@ def test_prediction_api_key_registry_client_client_options( # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): - client = client_class() + client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): - client = client_class() + client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -349,7 +349,7 @@ def test_prediction_api_key_registry_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None @@ -426,6 +426,90 @@ def test_prediction_api_key_registry_client_mtls_env_auto( ) +@pytest.mark.parametrize( + "client_class", + [PredictionApiKeyRegistryClient, PredictionApiKeyRegistryAsyncClient], +) +@mock.patch.object( + PredictionApiKeyRegistryClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PredictionApiKeyRegistryClient), +) +@mock.patch.object( + PredictionApiKeyRegistryAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PredictionApiKeyRegistryAsyncClient), +) +def test_prediction_api_key_registry_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + @pytest.mark.parametrize( "client_class,transport_class,transport_name", [ @@ -448,7 +532,7 @@ def test_prediction_api_key_registry_client_client_options_scopes( options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -462,28 +546,31 @@ def test_prediction_api_key_registry_client_client_options_scopes( @pytest.mark.parametrize( - "client_class,transport_class,transport_name", + "client_class,transport_class,transport_name,grpc_helpers", [ ( PredictionApiKeyRegistryClient, transports.PredictionApiKeyRegistryGrpcTransport, "grpc", + grpc_helpers, ), ( PredictionApiKeyRegistryAsyncClient, transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, "grpc_asyncio", + grpc_helpers_async, ), ], ) def test_prediction_api_key_registry_client_client_options_credentials_file( - client_class, transport_class, transport_name + client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -516,10 +603,80 @@ def test_prediction_api_key_registry_client_client_options_from_dict(): ) -def test_create_prediction_api_key_registration( - transport: str = "grpc", - request_type=prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + PredictionApiKeyRegistryClient, + transports.PredictionApiKeyRegistryGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + PredictionApiKeyRegistryAsyncClient, + transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_prediction_api_key_registry_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers ): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "recommendationengine.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="recommendationengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + prediction_apikey_registry_service.CreatePredictionApiKeyRegistrationRequest, + dict, + ], +) +def test_create_prediction_api_key_registration(request_type, transport: str = "grpc"): client = PredictionApiKeyRegistryClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -553,10 +710,6 @@ def test_create_prediction_api_key_registration( assert response.api_key == "api_key_value" -def test_create_prediction_api_key_registration_from_dict(): - test_create_prediction_api_key_registration(request_type=dict) - - 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. @@ -713,12 +866,14 @@ 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( + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].prediction_api_key_registration + mock_val = prediction_apikey_registry_service.PredictionApiKeyRegistration( api_key="api_key_value" ) + assert arg == mock_val def test_create_prediction_api_key_registration_flattened_error(): @@ -769,12 +924,14 @@ 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( + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].prediction_api_key_registration + mock_val = prediction_apikey_registry_service.PredictionApiKeyRegistration( api_key="api_key_value" ) + assert arg == mock_val @pytest.mark.asyncio @@ -795,10 +952,14 @@ async def test_create_prediction_api_key_registration_flattened_error_async(): ) -def test_list_prediction_api_key_registrations( - transport: str = "grpc", - request_type=prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, -): +@pytest.mark.parametrize( + "request_type", + [ + prediction_apikey_registry_service.ListPredictionApiKeyRegistrationsRequest, + dict, + ], +) +def test_list_prediction_api_key_registrations(request_type, transport: str = "grpc"): client = PredictionApiKeyRegistryClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -830,10 +991,6 @@ def test_list_prediction_api_key_registrations( assert response.next_page_token == "next_page_token_value" -def test_list_prediction_api_key_registrations_from_dict(): - test_list_prediction_api_key_registrations(request_type=dict) - - 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. @@ -983,7 +1140,9 @@ 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" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val def test_list_prediction_api_key_registrations_flattened_error(): @@ -1028,7 +1187,9 @@ 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" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val @pytest.mark.asyncio @@ -1046,9 +1207,9 @@ async def test_list_prediction_api_key_registrations_flattened_error_async(): ) -def test_list_prediction_api_key_registrations_pager(): +def test_list_prediction_api_key_registrations_pager(transport_name: str = "grpc"): client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1101,9 +1262,9 @@ def test_list_prediction_api_key_registrations_pager(): ) -def test_list_prediction_api_key_registrations_pages(): +def test_list_prediction_api_key_registrations_pages(transport_name: str = "grpc"): client = PredictionApiKeyRegistryClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1244,10 +1405,14 @@ async def test_list_prediction_api_key_registrations_async_pages(): assert page_.raw_page.next_page_token == token -def test_delete_prediction_api_key_registration( - transport: str = "grpc", - request_type=prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, -): +@pytest.mark.parametrize( + "request_type", + [ + prediction_apikey_registry_service.DeletePredictionApiKeyRegistrationRequest, + dict, + ], +) +def test_delete_prediction_api_key_registration(request_type, transport: str = "grpc"): client = PredictionApiKeyRegistryClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1276,10 +1441,6 @@ def test_delete_prediction_api_key_registration( assert response is None -def test_delete_prediction_api_key_registration_from_dict(): - test_delete_prediction_api_key_registration(request_type=dict) - - 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. @@ -1418,7 +1579,9 @@ 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" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val def test_delete_prediction_api_key_registration_flattened_error(): @@ -1459,7 +1622,9 @@ 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" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val @pytest.mark.asyncio @@ -1497,6 +1662,25 @@ def test_credentials_transport_error(): transport=transport, ) + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionApiKeyRegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + client_options=options, transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionApiKeyRegistryClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + # It is an error to provide scopes and a transport instance. transport = transports.PredictionApiKeyRegistryGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2043,7 +2227,7 @@ def test_parse_common_location_path(): assert expected == actual -def test_client_withDEFAULT_CLIENT_INFO(): +def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( @@ -2108,3 +2292,39 @@ def test_client_ctx(): with client: pass close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + PredictionApiKeyRegistryClient, + transports.PredictionApiKeyRegistryGrpcTransport, + ), + ( + PredictionApiKeyRegistryAsyncClient, + transports.PredictionApiKeyRegistryGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py b/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py index 9a901b3c..a065960f 100644 --- a/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py +++ b/tests/unit/gapic/recommendationengine_v1beta1/test_prediction_service.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -258,20 +258,20 @@ def test_prediction_service_client_client_options( # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): - client = client_class() + client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): - client = client_class() + client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -340,7 +340,7 @@ def test_prediction_service_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None @@ -417,6 +417,87 @@ def test_prediction_service_client_mtls_env_auto( ) +@pytest.mark.parametrize( + "client_class", [PredictionServiceClient, PredictionServiceAsyncClient] +) +@mock.patch.object( + PredictionServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PredictionServiceClient), +) +@mock.patch.object( + PredictionServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PredictionServiceAsyncClient), +) +def test_prediction_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + @pytest.mark.parametrize( "client_class,transport_class,transport_name", [ @@ -435,7 +516,7 @@ def test_prediction_service_client_client_options_scopes( options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -449,24 +530,31 @@ def test_prediction_service_client_client_options_scopes( @pytest.mark.parametrize( - "client_class,transport_class,transport_name", + "client_class,transport_class,transport_name,grpc_helpers", [ - (PredictionServiceClient, transports.PredictionServiceGrpcTransport, "grpc"), + ( + PredictionServiceClient, + transports.PredictionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), ( PredictionServiceAsyncClient, transports.PredictionServiceGrpcAsyncIOTransport, "grpc_asyncio", + grpc_helpers_async, ), ], ) def test_prediction_service_client_client_options_credentials_file( - client_class, transport_class, transport_name + client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -499,9 +587,74 @@ def test_prediction_service_client_client_options_from_dict(): ) -def test_predict( - transport: str = "grpc", request_type=prediction_service.PredictRequest +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + PredictionServiceClient, + transports.PredictionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + PredictionServiceAsyncClient, + transports.PredictionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_prediction_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers ): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "recommendationengine.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="recommendationengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [prediction_service.PredictRequest, dict,]) +def test_predict(request_type, transport: str = "grpc"): client = PredictionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -534,10 +687,6 @@ def test_predict( assert response.next_page_token == "next_page_token_value" -def test_predict_from_dict(): - test_predict(request_type=dict) - - 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. @@ -667,10 +816,12 @@ 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" - ) + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].user_event + mock_val = gcr_user_event.UserEvent(event_type="event_type_value") + assert arg == mock_val def test_predict_flattened_error(): @@ -711,10 +862,12 @@ 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" - ) + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].user_event + mock_val = gcr_user_event.UserEvent(event_type="event_type_value") + assert arg == mock_val @pytest.mark.asyncio @@ -733,8 +886,10 @@ async def test_predict_flattened_error_async(): ) -def test_predict_pager(): - client = PredictionServiceClient(credentials=ga_credentials.AnonymousCredentials,) +def test_predict_pager(transport_name: str = "grpc"): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.predict), "__call__") as call: @@ -778,8 +933,10 @@ def test_predict_pager(): ) -def test_predict_pages(): - client = PredictionServiceClient(credentials=ga_credentials.AnonymousCredentials,) +def test_predict_pages(transport_name: str = "grpc"): + client = PredictionServiceClient( + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.predict), "__call__") as call: @@ -917,6 +1074,23 @@ def test_credentials_transport_error(): transport=transport, ) + # It is an error to provide an api_key and a transport instance. + transport = transports.PredictionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient(client_options=options, transport=transport,) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PredictionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + # It is an error to provide scopes and a transport instance. transport = transports.PredictionServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -1419,7 +1593,7 @@ def test_parse_common_location_path(): assert expected == actual -def test_client_withDEFAULT_CLIENT_INFO(): +def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( @@ -1484,3 +1658,36 @@ def test_client_ctx(): with client: pass close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (PredictionServiceClient, transports.PredictionServiceGrpcTransport), + ( + PredictionServiceAsyncClient, + transports.PredictionServiceGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py b/tests/unit/gapic/recommendationengine_v1beta1/test_user_event_service.py index 7d9d76c3..699b1afc 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,5 @@ # -*- coding: utf-8 -*- -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async +from google.api_core import operation from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 from google.api_core import path_template @@ -265,20 +266,20 @@ def test_user_event_service_client_client_options( # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): - client = client_class() + client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): - client = client_class() + client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -347,7 +348,7 @@ def test_user_event_service_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None @@ -424,6 +425,87 @@ def test_user_event_service_client_mtls_env_auto( ) +@pytest.mark.parametrize( + "client_class", [UserEventServiceClient, UserEventServiceAsyncClient] +) +@mock.patch.object( + UserEventServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(UserEventServiceClient), +) +@mock.patch.object( + UserEventServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(UserEventServiceAsyncClient), +) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + @pytest.mark.parametrize( "client_class,transport_class,transport_name", [ @@ -442,7 +524,7 @@ def test_user_event_service_client_client_options_scopes( options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -456,24 +538,31 @@ def test_user_event_service_client_client_options_scopes( @pytest.mark.parametrize( - "client_class,transport_class,transport_name", + "client_class,transport_class,transport_name,grpc_helpers", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + ( + UserEventServiceClient, + transports.UserEventServiceGrpcTransport, + "grpc", + grpc_helpers, + ), ( UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", + grpc_helpers_async, ), ], ) def test_user_event_service_client_client_options_credentials_file( - client_class, transport_class, transport_name + client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -506,9 +595,76 @@ def test_user_event_service_client_client_options_from_dict(): ) -def test_write_user_event( - transport: str = "grpc", request_type=user_event_service.WriteUserEventRequest +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + UserEventServiceClient, + transports.UserEventServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + UserEventServiceAsyncClient, + transports.UserEventServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_user_event_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers ): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "recommendationengine.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="recommendationengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", [user_event_service.WriteUserEventRequest, dict,] +) +def test_write_user_event(request_type, transport: str = "grpc"): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -537,10 +693,6 @@ def test_write_user_event( assert response.event_source == gcr_user_event.UserEvent.EventSource.AUTOML -def test_write_user_event_from_dict(): - test_write_user_event(request_type=dict) - - 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. @@ -667,10 +819,12 @@ 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" - ) + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user_event + mock_val = gcr_user_event.UserEvent(event_type="event_type_value") + assert arg == mock_val def test_write_user_event_flattened_error(): @@ -711,10 +865,12 @@ 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" - ) + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user_event + mock_val = gcr_user_event.UserEvent(event_type="event_type_value") + assert arg == mock_val @pytest.mark.asyncio @@ -733,9 +889,10 @@ async def test_write_user_event_flattened_error_async(): ) -def test_collect_user_event( - transport: str = "grpc", request_type=user_event_service.CollectUserEventRequest -): +@pytest.mark.parametrize( + "request_type", [user_event_service.CollectUserEventRequest, dict,] +) +def test_collect_user_event(request_type, transport: str = "grpc"): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -765,10 +922,6 @@ def test_collect_user_event( assert response.data == b"data_blob" -def test_collect_user_event_from_dict(): - test_collect_user_event(request_type=dict) - - 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. @@ -904,10 +1057,18 @@ 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 + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user_event + mock_val = "user_event_value" + assert arg == mock_val + arg = args[0].uri + mock_val = "uri_value" + assert arg == mock_val + arg = args[0].ets + mock_val = 332 + assert arg == mock_val def test_collect_user_event_flattened_error(): @@ -954,10 +1115,18 @@ 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 + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user_event + mock_val = "user_event_value" + assert arg == mock_val + arg = args[0].uri + mock_val = "uri_value" + assert arg == mock_val + arg = args[0].ets + mock_val = 332 + assert arg == mock_val @pytest.mark.asyncio @@ -978,9 +1147,10 @@ async def test_collect_user_event_flattened_error_async(): ) -def test_list_user_events( - transport: str = "grpc", request_type=user_event_service.ListUserEventsRequest -): +@pytest.mark.parametrize( + "request_type", [user_event_service.ListUserEventsRequest, dict,] +) +def test_list_user_events(request_type, transport: str = "grpc"): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1007,10 +1177,6 @@ def test_list_user_events( assert response.next_page_token == "next_page_token_value" -def test_list_user_events_from_dict(): - test_list_user_events(request_type=dict) - - 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. @@ -1134,8 +1300,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" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val def test_list_user_events_flattened_error(): @@ -1175,8 +1345,12 @@ 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" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val @pytest.mark.asyncio @@ -1195,8 +1369,10 @@ async def test_list_user_events_flattened_error_async(): ) -def test_list_user_events_pager(): - client = UserEventServiceClient(credentials=ga_credentials.AnonymousCredentials,) +def test_list_user_events_pager(transport_name: str = "grpc"): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_user_events), "__call__") as call: @@ -1235,8 +1411,10 @@ def test_list_user_events_pager(): assert all(isinstance(i, user_event.UserEvent) for i in results) -def test_list_user_events_pages(): - client = UserEventServiceClient(credentials=ga_credentials.AnonymousCredentials,) +def test_list_user_events_pages(transport_name: str = "grpc"): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_user_events), "__call__") as call: @@ -1345,9 +1523,10 @@ async def test_list_user_events_async_pages(): assert page_.raw_page.next_page_token == token -def test_purge_user_events( - transport: str = "grpc", request_type=user_event_service.PurgeUserEventsRequest -): +@pytest.mark.parametrize( + "request_type", [user_event_service.PurgeUserEventsRequest, dict,] +) +def test_purge_user_events(request_type, transport: str = "grpc"): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1373,10 +1552,6 @@ def test_purge_user_events( assert isinstance(response, future.Future) -def test_purge_user_events_from_dict(): - test_purge_user_events(request_type=dict) - - 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. @@ -1507,9 +1682,15 @@ 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 + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val + arg = args[0].force + mock_val = True + assert arg == mock_val def test_purge_user_events_flattened_error(): @@ -1552,9 +1733,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 + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].filter + mock_val = "filter_value" + assert arg == mock_val + arg = args[0].force + mock_val = True + assert arg == mock_val @pytest.mark.asyncio @@ -1574,9 +1761,8 @@ async def test_purge_user_events_flattened_error_async(): ) -def test_import_user_events( - transport: str = "grpc", request_type=import_.ImportUserEventsRequest -): +@pytest.mark.parametrize("request_type", [import_.ImportUserEventsRequest, dict,]) +def test_import_user_events(request_type, transport: str = "grpc"): client = UserEventServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1602,10 +1788,6 @@ def test_import_user_events( assert isinstance(response, future.Future) -def test_import_user_events_from_dict(): - test_import_user_events(request_type=dict) - - 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. @@ -1742,16 +1924,22 @@ 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( + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].request_id + mock_val = "request_id_value" + assert arg == mock_val + arg = args[0].input_config + mock_val = import_.InputConfig( catalog_inline_source=import_.CatalogInlineSource( catalog_items=[catalog.CatalogItem(id="id_value")] ) ) - assert args[0].errors_config == import_.ImportErrorsConfig( - gcs_prefix="gcs_prefix_value" - ) + assert arg == mock_val + arg = args[0].errors_config + mock_val = import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value") + assert arg == mock_val def test_import_user_events_flattened_error(): @@ -1806,16 +1994,22 @@ 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( + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].request_id + mock_val = "request_id_value" + assert arg == mock_val + arg = args[0].input_config + mock_val = import_.InputConfig( catalog_inline_source=import_.CatalogInlineSource( catalog_items=[catalog.CatalogItem(id="id_value")] ) ) - assert args[0].errors_config == import_.ImportErrorsConfig( - gcs_prefix="gcs_prefix_value" - ) + assert arg == mock_val + arg = args[0].errors_config + mock_val = import_.ImportErrorsConfig(gcs_prefix="gcs_prefix_value") + assert arg == mock_val @pytest.mark.asyncio @@ -1860,6 +2054,23 @@ def test_credentials_transport_error(): transport=transport, ) + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient(client_options=options, transport=transport,) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + # It is an error to provide scopes and a transport instance. transport = transports.UserEventServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2393,7 +2604,7 @@ def test_parse_common_location_path(): assert expected == actual -def test_client_withDEFAULT_CLIENT_INFO(): +def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( @@ -2458,3 +2669,33 @@ def test_client_ctx(): with client: pass close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + )