diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index cb89b2e..b668c04 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,17 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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:ec49167c606648a063d1222220b48119c912562849a0528f35bfb592a9f72737 + digest: sha256:ed1f9983d5a935a89fe8085e8bb97d94e41015252c5b6c9771257cf8624367e6 + diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index be888a9..e446644 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 - -/samples/ @googleapis/python-samples-owners +# @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 4507ad0..466597e 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 0000000..d4ca941 --- /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 0000000..f7b8344 --- /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 0000000..1e8b05c --- /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 0000000..074ee25 --- /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 f4bd99b..7f6a2ab 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-service-usage 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 67ea992..003838c 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,8 +23,18 @@ env_vars: { value: "github/python-service-usage/.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 9a9c58e..ef27c01 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -2,14 +2,15 @@ "name": "serviceusage", "name_pretty": "Service Usage", "product_documentation": "https://cloud.google.com/service-usage", - "client_documentation": "https://googleapis.dev/python/serviceusage/latest", + "client_documentation": "https://cloud.google.com/python/docs/reference/serviceusage/latest", "issue_tracker": "", - "release_level": "ga", + "release_level": "stable", "language": "python", "library_type": "GAPIC_AUTO", "repo": "googleapis/python-service-usage", "distribution_name": "google-cloud-service-usage", "api_id": "serviceusage.googleapis.com", "default_version": "v1", - "codeowner_team": "" + "codeowner_team": "", + "api_shortname": "serviceusage" } diff --git a/CHANGELOG.md b/CHANGELOG.md index a8bd6cc..513e058 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## [1.3.0](https://github.com/googleapis/python-service-usage/compare/v1.2.1...v1.3.0) (2022-02-26) + + +### Features + +* add api key support ([#74](https://github.com/googleapis/python-service-usage/issues/74)) ([c9cf774](https://github.com/googleapis/python-service-usage/commit/c9cf774ba8082ce7026acd582817e84b63d39fbe)) + + +### Bug Fixes + +* resolve DuplicateCredentialArgs error when using credentials_file ([27fb0c2](https://github.com/googleapis/python-service-usage/commit/27fb0c270dc776862f282159c9a637aa5900ced7)) + + +### Documentation + +* add generated snippets ([#79](https://github.com/googleapis/python-service-usage/issues/79)) ([dee08f1](https://github.com/googleapis/python-service-usage/commit/dee08f1d654cb5e04955ca51c824f77b13c000b9)) + ### [1.2.1](https://www.github.com/googleapis/python-service-usage/compare/v1.2.0...v1.2.1) (2021-11-01) diff --git a/README.rst b/README.rst index e877deb..90cc51e 100644 --- a/README.rst +++ b/README.rst @@ -17,7 +17,7 @@ well as services created using Cloud Endpoints. .. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-service-usage.svg :target: https://pypi.org/project/google-cloud-service-usage/ .. _Service Usage: https://cloud.google.com/service-usage -.. _Client Library Documentation: https://googleapis.dev/python/serviceusage/latest +.. _Client Library Documentation: https://cloud.google.com/python/docs/reference/serviceusage/latest .. _Product Documentation: https://cloud.google.com/service-usage/docs Quick Start diff --git a/google/cloud/service_usage/__init__.py b/google/cloud/service_usage/__init__.py index bedf716..ffdb561 100644 --- a/google/cloud/service_usage/__init__.py +++ b/google/cloud/service_usage/__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/service_usage_v1/__init__.py b/google/cloud/service_usage_v1/__init__.py index 5abf9da..70e93a3 100644 --- a/google/cloud/service_usage_v1/__init__.py +++ b/google/cloud/service_usage_v1/__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/service_usage_v1/services/__init__.py b/google/cloud/service_usage_v1/services/__init__.py index 4de6597..e8e1c38 100644 --- a/google/cloud/service_usage_v1/services/__init__.py +++ b/google/cloud/service_usage_v1/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/service_usage_v1/services/service_usage/__init__.py b/google/cloud/service_usage_v1/services/service_usage/__init__.py index 53659de..27b2a87 100644 --- a/google/cloud/service_usage_v1/services/service_usage/__init__.py +++ b/google/cloud/service_usage_v1/services/service_usage/__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/service_usage_v1/services/service_usage/async_client.py b/google/cloud/service_usage_v1/services/service_usage/async_client.py index c1774e6..8830a9a 100644 --- a/google/cloud/service_usage_v1/services/service_usage/async_client.py +++ b/google/cloud/service_usage_v1/services/service_usage/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 @@ -106,6 +109,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 ServiceUsageClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + @property def transport(self) -> ServiceUsageTransport: """Returns the transport used by the client instance. @@ -177,6 +216,29 @@ async def enable_service( r"""Enable a service so that it can be used with a project. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_enable_service(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.EnableServiceRequest( + ) + + # Make the request + operation = client.enable_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.EnableServiceRequest, dict]): The request object. Request message for the @@ -245,6 +307,29 @@ async def disable_service( ``FAILED_PRECONDITION`` status if the target service is not currently enabled. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_disable_service(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.DisableServiceRequest( + ) + + # Make the request + operation = client.disable_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.DisableServiceRequest, dict]): The request object. Request message for the @@ -307,6 +392,25 @@ async def get_service( r"""Returns the service configuration and enabled state for a given service. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_get_service(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.GetServiceRequest( + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.GetServiceRequest, dict]): The request object. Request message for the `GetService` @@ -369,6 +473,26 @@ async def list_services( which provides higher throughput and richer filtering capability. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_list_services(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.ListServicesRequest( + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.ListServicesRequest, dict]): The request object. Request message for the @@ -429,6 +553,29 @@ async def batch_enable_services( no state changes occur. To enable a single service, use the ``EnableService`` method instead. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_batch_enable_services(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.BatchEnableServicesRequest( + ) + + # Make the request + operation = client.batch_enable_services(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.BatchEnableServicesRequest, dict]): The request object. Request message for the @@ -491,6 +638,25 @@ async def batch_get_services( r"""Returns the service configurations and enabled states for a given list of services. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_batch_get_services(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.BatchGetServicesRequest( + ) + + # Make the request + response = client.batch_get_services(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.BatchGetServicesRequest, dict]): The request object. Request message for the diff --git a/google/cloud/service_usage_v1/services/service_usage/client.py b/google/cloud/service_usage_v1/services/service_usage/client.py index 61a15f2..e0f264a 100644 --- a/google/cloud/service_usage_v1/services/service_usage/client.py +++ b/google/cloud/service_usage_v1/services/service_usage/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 @@ -223,6 +225,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, *, @@ -273,50 +342,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, ServiceUsageTransport): # transport is a ServiceUsageTransport 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." @@ -328,6 +369,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, @@ -351,6 +401,29 @@ def enable_service( r"""Enable a service so that it can be used with a project. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_enable_service(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.EnableServiceRequest( + ) + + # Make the request + operation = client.enable_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.EnableServiceRequest, dict]): The request object. Request message for the @@ -420,6 +493,29 @@ def disable_service( ``FAILED_PRECONDITION`` status if the target service is not currently enabled. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_disable_service(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.DisableServiceRequest( + ) + + # Make the request + operation = client.disable_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.DisableServiceRequest, dict]): The request object. Request message for the @@ -483,6 +579,25 @@ def get_service( r"""Returns the service configuration and enabled state for a given service. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_get_service(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.GetServiceRequest( + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.GetServiceRequest, dict]): The request object. Request message for the `GetService` @@ -546,6 +661,26 @@ def list_services( which provides higher throughput and richer filtering capability. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_list_services(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.ListServicesRequest( + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.ListServicesRequest, dict]): The request object. Request message for the @@ -607,6 +742,29 @@ def batch_enable_services( no state changes occur. To enable a single service, use the ``EnableService`` method instead. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_batch_enable_services(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.BatchEnableServicesRequest( + ) + + # Make the request + operation = client.batch_enable_services(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.BatchEnableServicesRequest, dict]): The request object. Request message for the @@ -670,6 +828,25 @@ def batch_get_services( r"""Returns the service configurations and enabled states for a given list of services. + + .. code-block:: python + + from google.cloud import service_usage_v1 + + def sample_batch_get_services(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.BatchGetServicesRequest( + ) + + # Make the request + response = client.batch_get_services(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.service_usage_v1.types.BatchGetServicesRequest, dict]): The request object. Request message for the diff --git a/google/cloud/service_usage_v1/services/service_usage/pagers.py b/google/cloud/service_usage_v1/services/service_usage/pagers.py index 854acd3..9473d67 100644 --- a/google/cloud/service_usage_v1/services/service_usage/pagers.py +++ b/google/cloud/service_usage_v1/services/service_usage/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/service_usage_v1/services/service_usage/transports/__init__.py b/google/cloud/service_usage_v1/services/service_usage/transports/__init__.py index 9e08b4b..6a69120 100644 --- a/google/cloud/service_usage_v1/services/service_usage/transports/__init__.py +++ b/google/cloud/service_usage_v1/services/service_usage/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/service_usage_v1/services/service_usage/transports/base.py b/google/cloud/service_usage_v1/services/service_usage/transports/base.py index 3c39880..e6b8dc2 100644 --- a/google/cloud/service_usage_v1/services/service_usage/transports/base.py +++ b/google/cloud/service_usage_v1/services/service_usage/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 @@ -108,7 +108,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/service_usage_v1/services/service_usage/transports/grpc.py b/google/cloud/service_usage_v1/services/service_usage/transports/grpc.py index 5f2318b..ec53bc5 100644 --- a/google/cloud/service_usage_v1/services/service_usage/transports/grpc.py +++ b/google/cloud/service_usage_v1/services/service_usage/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 @@ -167,8 +167,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.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/service_usage_v1/services/service_usage/transports/grpc_asyncio.py b/google/cloud/service_usage_v1/services/service_usage/transports/grpc_asyncio.py index ab95ce1..5f49896 100644 --- a/google/cloud/service_usage_v1/services/service_usage/transports/grpc_asyncio.py +++ b/google/cloud/service_usage_v1/services/service_usage/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 @@ -212,8 +212,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, @@ -243,7 +246,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/service_usage_v1/types/__init__.py b/google/cloud/service_usage_v1/types/__init__.py index 8fa0708..9bb0b9e 100644 --- a/google/cloud/service_usage_v1/types/__init__.py +++ b/google/cloud/service_usage_v1/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/service_usage_v1/types/resources.py b/google/cloud/service_usage_v1/types/resources.py index 9e46bdd..ae890ab 100644 --- a/google/cloud/service_usage_v1/types/resources.py +++ b/google/cloud/service_usage_v1/types/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/service_usage_v1/types/serviceusage.py b/google/cloud/service_usage_v1/types/serviceusage.py index fc5a12c..27651e6 100644 --- a/google/cloud/service_usage_v1/types/serviceusage.py +++ b/google/cloud/service_usage_v1/types/serviceusage.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/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_enable_services_async.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_enable_services_async.py new file mode 100644 index 0000000..88d0a3c --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_enable_services_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchEnableServices +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_BatchEnableServices_async] +from google.cloud import service_usage_v1 + + +async def sample_batch_enable_services(): + # Create a client + client = service_usage_v1.ServiceUsageAsyncClient() + + # Initialize request argument(s) + request = service_usage_v1.BatchEnableServicesRequest( + ) + + # Make the request + operation = client.batch_enable_services(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_BatchEnableServices_async] diff --git a/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_enable_services_sync.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_enable_services_sync.py new file mode 100644 index 0000000..629ab21 --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_enable_services_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchEnableServices +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_BatchEnableServices_sync] +from google.cloud import service_usage_v1 + + +def sample_batch_enable_services(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.BatchEnableServicesRequest( + ) + + # Make the request + operation = client.batch_enable_services(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_BatchEnableServices_sync] diff --git a/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_get_services_async.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_get_services_async.py new file mode 100644 index 0000000..1935590 --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_get_services_async.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchGetServices +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_BatchGetServices_async] +from google.cloud import service_usage_v1 + + +async def sample_batch_get_services(): + # Create a client + client = service_usage_v1.ServiceUsageAsyncClient() + + # Initialize request argument(s) + request = service_usage_v1.BatchGetServicesRequest( + ) + + # Make the request + response = await client.batch_get_services(request=request) + + # Handle the response + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_BatchGetServices_async] diff --git a/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_get_services_sync.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_get_services_sync.py new file mode 100644 index 0000000..4531386 --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_batch_get_services_sync.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchGetServices +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_BatchGetServices_sync] +from google.cloud import service_usage_v1 + + +def sample_batch_get_services(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.BatchGetServicesRequest( + ) + + # Make the request + response = client.batch_get_services(request=request) + + # Handle the response + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_BatchGetServices_sync] diff --git a/samples/generated_samples/serviceusage_v1_generated_service_usage_disable_service_async.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_disable_service_async.py new file mode 100644 index 0000000..38384e2 --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_disable_service_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DisableService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_DisableService_async] +from google.cloud import service_usage_v1 + + +async def sample_disable_service(): + # Create a client + client = service_usage_v1.ServiceUsageAsyncClient() + + # Initialize request argument(s) + request = service_usage_v1.DisableServiceRequest( + ) + + # Make the request + operation = client.disable_service(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_DisableService_async] diff --git a/samples/generated_samples/serviceusage_v1_generated_service_usage_disable_service_sync.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_disable_service_sync.py new file mode 100644 index 0000000..bda7766 --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_disable_service_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DisableService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_DisableService_sync] +from google.cloud import service_usage_v1 + + +def sample_disable_service(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.DisableServiceRequest( + ) + + # Make the request + operation = client.disable_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_DisableService_sync] diff --git a/samples/generated_samples/serviceusage_v1_generated_service_usage_enable_service_async.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_enable_service_async.py new file mode 100644 index 0000000..3cdbd9a --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_enable_service_async.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EnableService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_EnableService_async] +from google.cloud import service_usage_v1 + + +async def sample_enable_service(): + # Create a client + client = service_usage_v1.ServiceUsageAsyncClient() + + # Initialize request argument(s) + request = service_usage_v1.EnableServiceRequest( + ) + + # Make the request + operation = client.enable_service(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_EnableService_async] diff --git a/samples/generated_samples/serviceusage_v1_generated_service_usage_enable_service_sync.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_enable_service_sync.py new file mode 100644 index 0000000..e5d4254 --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_enable_service_sync.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EnableService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_EnableService_sync] +from google.cloud import service_usage_v1 + + +def sample_enable_service(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.EnableServiceRequest( + ) + + # Make the request + operation = client.enable_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_EnableService_sync] diff --git a/samples/generated_samples/serviceusage_v1_generated_service_usage_get_service_async.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_get_service_async.py new file mode 100644 index 0000000..0f28939 --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_get_service_async.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_GetService_async] +from google.cloud import service_usage_v1 + + +async def sample_get_service(): + # Create a client + client = service_usage_v1.ServiceUsageAsyncClient() + + # Initialize request argument(s) + request = service_usage_v1.GetServiceRequest( + ) + + # Make the request + response = await client.get_service(request=request) + + # Handle the response + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_GetService_async] diff --git a/samples/generated_samples/serviceusage_v1_generated_service_usage_get_service_sync.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_get_service_sync.py new file mode 100644 index 0000000..11a5444 --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_get_service_sync.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetService +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_GetService_sync] +from google.cloud import service_usage_v1 + + +def sample_get_service(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.GetServiceRequest( + ) + + # Make the request + response = client.get_service(request=request) + + # Handle the response + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_GetService_sync] diff --git a/samples/generated_samples/serviceusage_v1_generated_service_usage_list_services_async.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_list_services_async.py new file mode 100644 index 0000000..3939869 --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_list_services_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 ListServices +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_ListServices_async] +from google.cloud import service_usage_v1 + + +async def sample_list_services(): + # Create a client + client = service_usage_v1.ServiceUsageAsyncClient() + + # Initialize request argument(s) + request = service_usage_v1.ListServicesRequest( + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_ListServices_async] diff --git a/samples/generated_samples/serviceusage_v1_generated_service_usage_list_services_sync.py b/samples/generated_samples/serviceusage_v1_generated_service_usage_list_services_sync.py new file mode 100644 index 0000000..be7b978 --- /dev/null +++ b/samples/generated_samples/serviceusage_v1_generated_service_usage_list_services_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 ListServices +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-service-usage + + +# [START serviceusage_v1_generated_ServiceUsage_ListServices_sync] +from google.cloud import service_usage_v1 + + +def sample_list_services(): + # Create a client + client = service_usage_v1.ServiceUsageClient() + + # Initialize request argument(s) + request = service_usage_v1.ListServicesRequest( + ) + + # Make the request + page_result = client.list_services(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END serviceusage_v1_generated_ServiceUsage_ListServices_sync] diff --git a/samples/generated_samples/snippet_metadata_service usage_v1.json b/samples/generated_samples/snippet_metadata_service usage_v1.json new file mode 100644 index 0000000..25261c9 --- /dev/null +++ b/samples/generated_samples/snippet_metadata_service usage_v1.json @@ -0,0 +1,538 @@ +{ + "snippets": [ + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "BatchEnableServices" + } + }, + "file": "serviceusage_v1_generated_service_usage_batch_enable_services_async.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_BatchEnableServices_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "BatchEnableServices" + } + }, + "file": "serviceusage_v1_generated_service_usage_batch_enable_services_sync.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_BatchEnableServices_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "BatchGetServices" + } + }, + "file": "serviceusage_v1_generated_service_usage_batch_get_services_async.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_BatchGetServices_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "BatchGetServices" + } + }, + "file": "serviceusage_v1_generated_service_usage_batch_get_services_sync.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_BatchGetServices_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "DisableService" + } + }, + "file": "serviceusage_v1_generated_service_usage_disable_service_async.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_DisableService_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "DisableService" + } + }, + "file": "serviceusage_v1_generated_service_usage_disable_service_sync.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_DisableService_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "EnableService" + } + }, + "file": "serviceusage_v1_generated_service_usage_enable_service_async.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_EnableService_async", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "EnableService" + } + }, + "file": "serviceusage_v1_generated_service_usage_enable_service_sync.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_EnableService_sync", + "segments": [ + { + "end": 47, + "start": 27, + "type": "FULL" + }, + { + "end": 47, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 44, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 48, + "start": 45, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "GetService" + } + }, + "file": "serviceusage_v1_generated_service_usage_get_service_async.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_GetService_async", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "GetService" + } + }, + "file": "serviceusage_v1_generated_service_usage_get_service_sync.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_GetService_sync", + "segments": [ + { + "end": 43, + "start": 27, + "type": "FULL" + }, + { + "end": 43, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 44, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "ListServices" + } + }, + "file": "serviceusage_v1_generated_service_usage_list_services_async.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_ListServices_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "ServiceUsage" + }, + "shortName": "ListServices" + } + }, + "file": "serviceusage_v1_generated_service_usage_list_services_sync.py", + "regionTag": "serviceusage_v1_generated_ServiceUsage_ListServices_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 37, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 40, + "start": 38, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 41, + "type": "RESPONSE_HANDLING" + } + ] + } + ] +} diff --git a/scripts/fixup_service_usage_v1_keywords.py b/scripts/fixup_service_usage_v1_keywords.py index dbcc0ed..c8851cf 100644 --- a/scripts/fixup_service_usage_v1_keywords.py +++ b/scripts/fixup_service_usage_v1_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 72fa8d6..830b0bb 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ name = "google-cloud-service-usage" description = "Service Usage API client library" -version = "1.2.1" +version = "1.3.0" release_status = "Development Status :: 5 - Production/Stable" url = "https://github.com/googleapis/python-service-usage" dependencies = [ diff --git a/tests/__init__.py b/tests/__init__.py index 4de6597..e8e1c38 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 4de6597..e8e1c38 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 4de6597..e8e1c38 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/service_usage_v1/__init__.py b/tests/unit/gapic/service_usage_v1/__init__.py index 4de6597..e8e1c38 100644 --- a/tests/unit/gapic/service_usage_v1/__init__.py +++ b/tests/unit/gapic/service_usage_v1/__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/service_usage_v1/test_service_usage.py b/tests/unit/gapic/service_usage_v1/test_service_usage.py index 2b79e01..a78448a 100644 --- a/tests/unit/gapic/service_usage_v1/test_service_usage.py +++ b/tests/unit/gapic/service_usage_v1/test_service_usage.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 @@ -242,20 +243,20 @@ def test_service_usage_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, @@ -312,7 +313,7 @@ def test_service_usage_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 @@ -389,6 +390,83 @@ def test_service_usage_client_mtls_env_auto( ) +@pytest.mark.parametrize("client_class", [ServiceUsageClient, ServiceUsageAsyncClient]) +@mock.patch.object( + ServiceUsageClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceUsageClient) +) +@mock.patch.object( + ServiceUsageAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ServiceUsageAsyncClient), +) +def test_service_usage_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", [ @@ -407,7 +485,7 @@ def test_service_usage_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, @@ -421,24 +499,31 @@ def test_service_usage_client_client_options_scopes( @pytest.mark.parametrize( - "client_class,transport_class,transport_name", + "client_class,transport_class,transport_name,grpc_helpers", [ - (ServiceUsageClient, transports.ServiceUsageGrpcTransport, "grpc"), + ( + ServiceUsageClient, + transports.ServiceUsageGrpcTransport, + "grpc", + grpc_helpers, + ), ( ServiceUsageAsyncClient, transports.ServiceUsageGrpcAsyncIOTransport, "grpc_asyncio", + grpc_helpers_async, ), ], ) def test_service_usage_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", @@ -469,9 +554,78 @@ def test_service_usage_client_client_options_from_dict(): ) -def test_enable_service( - transport: str = "grpc", request_type=serviceusage.EnableServiceRequest +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + ServiceUsageClient, + transports.ServiceUsageGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + ServiceUsageAsyncClient, + transports.ServiceUsageGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_service_usage_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( + "serviceusage.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/service.management", + ), + scopes=None, + default_host="serviceusage.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [serviceusage.EnableServiceRequest, dict,]) +def test_enable_service(request_type, transport: str = "grpc"): client = ServiceUsageClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -495,10 +649,6 @@ def test_enable_service( assert isinstance(response, future.Future) -def test_enable_service_from_dict(): - test_enable_service(request_type=dict) - - def test_enable_service_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -599,9 +749,8 @@ async def test_enable_service_field_headers_async(): assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] -def test_disable_service( - transport: str = "grpc", request_type=serviceusage.DisableServiceRequest -): +@pytest.mark.parametrize("request_type", [serviceusage.DisableServiceRequest, dict,]) +def test_disable_service(request_type, transport: str = "grpc"): client = ServiceUsageClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -625,10 +774,6 @@ def test_disable_service( assert isinstance(response, future.Future) -def test_disable_service_from_dict(): - test_disable_service(request_type=dict) - - def test_disable_service_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -729,9 +874,8 @@ async def test_disable_service_field_headers_async(): assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] -def test_get_service( - transport: str = "grpc", request_type=serviceusage.GetServiceRequest -): +@pytest.mark.parametrize("request_type", [serviceusage.GetServiceRequest, dict,]) +def test_get_service(request_type, transport: str = "grpc"): client = ServiceUsageClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -760,10 +904,6 @@ def test_get_service( assert response.state == resources.State.DISABLED -def test_get_service_from_dict(): - test_get_service(request_type=dict) - - def test_get_service_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -869,9 +1009,8 @@ async def test_get_service_field_headers_async(): assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] -def test_list_services( - transport: str = "grpc", request_type=serviceusage.ListServicesRequest -): +@pytest.mark.parametrize("request_type", [serviceusage.ListServicesRequest, dict,]) +def test_list_services(request_type, transport: str = "grpc"): client = ServiceUsageClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -898,10 +1037,6 @@ def test_list_services( assert response.next_page_token == "next_page_token_value" -def test_list_services_from_dict(): - test_list_services(request_type=dict) - - def test_list_services_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -1003,8 +1138,10 @@ async def test_list_services_field_headers_async(): assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] -def test_list_services_pager(): - client = ServiceUsageClient(credentials=ga_credentials.AnonymousCredentials,) +def test_list_services_pager(transport_name: str = "grpc"): + client = ServiceUsageClient( + 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_services), "__call__") as call: @@ -1041,8 +1178,10 @@ def test_list_services_pager(): assert all(isinstance(i, resources.Service) for i in results) -def test_list_services_pages(): - client = ServiceUsageClient(credentials=ga_credentials.AnonymousCredentials,) +def test_list_services_pages(transport_name: str = "grpc"): + client = ServiceUsageClient( + 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_services), "__call__") as call: @@ -1141,9 +1280,10 @@ async def test_list_services_async_pages(): assert page_.raw_page.next_page_token == token -def test_batch_enable_services( - transport: str = "grpc", request_type=serviceusage.BatchEnableServicesRequest -): +@pytest.mark.parametrize( + "request_type", [serviceusage.BatchEnableServicesRequest, dict,] +) +def test_batch_enable_services(request_type, transport: str = "grpc"): client = ServiceUsageClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1169,10 +1309,6 @@ def test_batch_enable_services( assert isinstance(response, future.Future) -def test_batch_enable_services_from_dict(): - test_batch_enable_services(request_type=dict) - - def test_batch_enable_services_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -1282,9 +1418,8 @@ async def test_batch_enable_services_field_headers_async(): assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] -def test_batch_get_services( - transport: str = "grpc", request_type=serviceusage.BatchGetServicesRequest -): +@pytest.mark.parametrize("request_type", [serviceusage.BatchGetServicesRequest, dict,]) +def test_batch_get_services(request_type, transport: str = "grpc"): client = ServiceUsageClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1310,10 +1445,6 @@ def test_batch_get_services( assert isinstance(response, serviceusage.BatchGetServicesResponse) -def test_batch_get_services_from_dict(): - test_batch_get_services(request_type=dict) - - def test_batch_get_services_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -1442,6 +1573,23 @@ def test_credentials_transport_error(): transport=transport, ) + # It is an error to provide an api_key and a transport instance. + transport = transports.ServiceUsageGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ServiceUsageClient(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 = ServiceUsageClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + # It is an error to provide scopes and a transport instance. transport = transports.ServiceUsageGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -1953,7 +2101,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( @@ -2018,3 +2166,33 @@ def test_client_ctx(): with client: pass close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (ServiceUsageClient, transports.ServiceUsageGrpcTransport), + (ServiceUsageAsyncClient, transports.ServiceUsageGrpcAsyncIOTransport), + ], +) +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, + )