From eb360aefdac09648852a073ef0837dc7c7b18679 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Sat, 22 May 2021 04:18:44 -0600 Subject: [PATCH] chore: update to gapic-generator-python 0.46.3 (#162) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: update to gapic-generator-python 0.46.3 * 🦉 Updates from OwlBot Co-authored-by: Owl Bot feat: add webm opus support fix: add async client to %name_%version/init.py chore: add autogenerated snippets chore: remove auth, policy, and options from the reserved names list feat: support self-signed JWT flow for service accounts chore: enable GAPIC metadata generation chore: sort subpackages in %namespace/%name/init.py --- docs/speech_v1p1beta1/adaptation.rst | 1 - google/cloud/speech/__init__.py | 8 +- google/cloud/speech_v1/__init__.py | 7 +- google/cloud/speech_v1/gapic_metadata.json | 53 ++ google/cloud/speech_v1/services/__init__.py | 1 - .../speech_v1/services/speech/__init__.py | 2 - .../speech_v1/services/speech/async_client.py | 35 +- .../cloud/speech_v1/services/speech/client.py | 65 +- .../services/speech/transports/__init__.py | 2 - .../services/speech/transports/base.py | 123 +++- .../services/speech/transports/grpc.py | 28 +- .../speech/transports/grpc_asyncio.py | 29 +- google/cloud/speech_v1/types/__init__.py | 2 - google/cloud/speech_v1/types/cloud_speech.py | 139 ++-- google/cloud/speech_v1p1beta1/__init__.py | 9 +- .../speech_v1p1beta1/gapic_metadata.json | 167 +++++ .../speech_v1p1beta1/services/__init__.py | 1 - .../services/adaptation/__init__.py | 2 - .../services/adaptation/async_client.py | 50 +- .../services/adaptation/client.py | 101 +-- .../services/adaptation/pagers.py | 6 +- .../adaptation/transports/__init__.py | 2 - .../services/adaptation/transports/base.py | 144 ++-- .../services/adaptation/transports/grpc.py | 32 +- .../adaptation/transports/grpc_asyncio.py | 33 +- .../services/speech/__init__.py | 2 - .../services/speech/async_client.py | 36 +- .../services/speech/client.py | 73 +- .../services/speech/transports/__init__.py | 2 - .../services/speech/transports/base.py | 123 +++- .../services/speech/transports/grpc.py | 28 +- .../speech/transports/grpc_asyncio.py | 29 +- .../cloud/speech_v1p1beta1/types/__init__.py | 2 - .../speech_v1p1beta1/types/cloud_speech.py | 186 ++--- .../types/cloud_speech_adaptation.py | 69 +- .../cloud/speech_v1p1beta1/types/resource.py | 27 +- scripts/fixup_speech_v1_keywords.py | 11 +- scripts/fixup_speech_v1p1beta1_keywords.py | 31 +- setup.py | 1 + testing/constraints-3.6.txt | 3 +- tests/__init__.py | 15 + tests/unit/__init__.py | 15 + tests/unit/gapic/__init__.py | 15 + tests/unit/gapic/speech_v1/__init__.py | 1 - tests/unit/gapic/speech_v1/test_speech.py | 335 ++++++--- tests/unit/gapic/speech_v1p1beta1/__init__.py | 1 - .../gapic/speech_v1p1beta1/test_adaptation.py | 668 ++++++++++-------- .../gapic/speech_v1p1beta1/test_speech.py | 343 ++++++--- 48 files changed, 1811 insertions(+), 1247 deletions(-) create mode 100644 google/cloud/speech_v1/gapic_metadata.json create mode 100644 google/cloud/speech_v1p1beta1/gapic_metadata.json create mode 100644 tests/__init__.py create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/gapic/__init__.py diff --git a/docs/speech_v1p1beta1/adaptation.rst b/docs/speech_v1p1beta1/adaptation.rst index 7236ba17..7644e3ca 100644 --- a/docs/speech_v1p1beta1/adaptation.rst +++ b/docs/speech_v1p1beta1/adaptation.rst @@ -5,7 +5,6 @@ Adaptation :members: :inherited-members: - .. automodule:: google.cloud.speech_v1p1beta1.services.adaptation.pagers :members: :inherited-members: diff --git a/google/cloud/speech/__init__.py b/google/cloud/speech/__init__.py index 0f805289..129e45b7 100644 --- a/google/cloud/speech/__init__.py +++ b/google/cloud/speech/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,8 +14,9 @@ # limitations under the License. # -from google.cloud.speech_v1.services.speech.async_client import SpeechAsyncClient from google.cloud.speech_v1 import SpeechClient +from google.cloud.speech_v1.services.speech.async_client import SpeechAsyncClient + from google.cloud.speech_v1.types.cloud_speech import LongRunningRecognizeMetadata from google.cloud.speech_v1.types.cloud_speech import LongRunningRecognizeRequest from google.cloud.speech_v1.types.cloud_speech import LongRunningRecognizeResponse @@ -36,6 +36,8 @@ from google.cloud.speech_v1.types.cloud_speech import WordInfo __all__ = ( + "SpeechClient", + "SpeechAsyncClient", "LongRunningRecognizeMetadata", "LongRunningRecognizeRequest", "LongRunningRecognizeResponse", @@ -45,8 +47,6 @@ "RecognizeRequest", "RecognizeResponse", "SpeakerDiarizationConfig", - "SpeechAsyncClient", - "SpeechClient", "SpeechContext", "SpeechRecognitionAlternative", "SpeechRecognitionResult", diff --git a/google/cloud/speech_v1/__init__.py b/google/cloud/speech_v1/__init__.py index 321f4c98..e4b1e2ea 100644 --- a/google/cloud/speech_v1/__init__.py +++ b/google/cloud/speech_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.speech import SpeechClient +from .services.speech import SpeechAsyncClient + from .types.cloud_speech import LongRunningRecognizeMetadata from .types.cloud_speech import LongRunningRecognizeRequest from .types.cloud_speech import LongRunningRecognizeResponse @@ -34,7 +35,6 @@ from .types.cloud_speech import StreamingRecognizeResponse from .types.cloud_speech import WordInfo - from google.cloud.speech_v1.helpers import SpeechHelpers @@ -43,6 +43,7 @@ class SpeechClient(SpeechHelpers, SpeechClient): __all__ = ( + "SpeechAsyncClient", "LongRunningRecognizeMetadata", "LongRunningRecognizeRequest", "LongRunningRecognizeResponse", @@ -52,6 +53,7 @@ class SpeechClient(SpeechHelpers, SpeechClient): "RecognizeRequest", "RecognizeResponse", "SpeakerDiarizationConfig", + "SpeechClient", "SpeechContext", "SpeechRecognitionAlternative", "SpeechRecognitionResult", @@ -60,5 +62,4 @@ class SpeechClient(SpeechHelpers, SpeechClient): "StreamingRecognizeRequest", "StreamingRecognizeResponse", "WordInfo", - "SpeechClient", ) diff --git a/google/cloud/speech_v1/gapic_metadata.json b/google/cloud/speech_v1/gapic_metadata.json new file mode 100644 index 00000000..8775ccc2 --- /dev/null +++ b/google/cloud/speech_v1/gapic_metadata.json @@ -0,0 +1,53 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.speech_v1", + "protoPackage": "google.cloud.speech.v1", + "schema": "1.0", + "services": { + "Speech": { + "clients": { + "grpc": { + "libraryClient": "SpeechClient", + "rpcs": { + "LongRunningRecognize": { + "methods": [ + "long_running_recognize" + ] + }, + "Recognize": { + "methods": [ + "recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "streaming_recognize" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SpeechAsyncClient", + "rpcs": { + "LongRunningRecognize": { + "methods": [ + "long_running_recognize" + ] + }, + "Recognize": { + "methods": [ + "recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "streaming_recognize" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/speech_v1/services/__init__.py b/google/cloud/speech_v1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/speech_v1/services/__init__.py +++ b/google/cloud/speech_v1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/speech_v1/services/speech/__init__.py b/google/cloud/speech_v1/services/speech/__init__.py index 72f816da..5a359701 100644 --- a/google/cloud/speech_v1/services/speech/__init__.py +++ b/google/cloud/speech_v1/services/speech/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SpeechClient from .async_client import SpeechAsyncClient diff --git a/google/cloud/speech_v1/services/speech/async_client.py b/google/cloud/speech_v1/services/speech/async_client.py index cfa5ec03..2c06a667 100644 --- a/google/cloud/speech_v1/services/speech/async_client.py +++ b/google/cloud/speech_v1/services/speech/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -31,17 +29,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.speech_v1.types import cloud_speech -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SpeechTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SpeechGrpcAsyncIOTransport from .client import SpeechClient @@ -59,24 +56,21 @@ class SpeechAsyncClient: parse_common_billing_account_path = staticmethod( SpeechClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SpeechClient.common_folder_path) parse_common_folder_path = staticmethod(SpeechClient.parse_common_folder_path) - common_organization_path = staticmethod(SpeechClient.common_organization_path) parse_common_organization_path = staticmethod( SpeechClient.parse_common_organization_path ) - common_project_path = staticmethod(SpeechClient.common_project_path) parse_common_project_path = staticmethod(SpeechClient.parse_common_project_path) - common_location_path = staticmethod(SpeechClient.common_location_path) parse_common_location_path = staticmethod(SpeechClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -91,7 +85,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -108,7 +102,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SpeechTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SpeechTransport: The transport used by the client instance. @@ -122,12 +116,12 @@ def transport(self) -> SpeechTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SpeechTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the speech client. + """Instantiates the speech client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -159,7 +153,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SpeechClient( credentials=credentials, transport=transport, @@ -199,7 +192,6 @@ async def recognize( This corresponds to the ``audio`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -227,7 +219,6 @@ async def recognize( # If we have keyword arguments corresponding to fields on the # request, apply these. - if config is not None: request.config = config if audio is not None: @@ -242,7 +233,8 @@ async def recognize( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=5000.0, ), @@ -292,7 +284,6 @@ async def long_running_recognize( This corresponds to the ``audio`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -325,7 +316,6 @@ async def long_running_recognize( # If we have keyword arguments corresponding to fields on the # request, apply these. - if config is not None: request.config = config if audio is not None: @@ -454,7 +444,8 @@ def streaming_recognize( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=5000.0, ), diff --git a/google/cloud/speech_v1/services/speech/client.py b/google/cloud/speech_v1/services/speech/client.py index e6b69c24..3cd92f97 100644 --- a/google/cloud/speech_v1/services/speech/client.py +++ b/google/cloud/speech_v1/services/speech/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -33,10 +31,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -45,8 +43,7 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.speech_v1.types import cloud_speech -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SpeechTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SpeechGrpcTransport from .transports.grpc_asyncio import SpeechGrpcAsyncIOTransport @@ -65,7 +62,7 @@ class SpeechClientMeta(type): _transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SpeechTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -88,7 +85,8 @@ class SpeechClient(metaclass=SpeechClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -122,7 +120,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -139,7 +138,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -158,16 +157,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SpeechTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SpeechTransport: The transport used by the client instance. + SpeechTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -180,7 +180,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -191,7 +191,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -202,7 +202,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -213,7 +213,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -227,12 +227,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SpeechTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the speech client. + """Instantiates the speech client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -287,9 +287,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -301,12 +302,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -321,8 +324,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -369,7 +372,6 @@ def recognize( This corresponds to the ``audio`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -399,10 +401,8 @@ def recognize( # there are no flattened fields. if not isinstance(request, cloud_speech.RecognizeRequest): request = cloud_speech.RecognizeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if config is not None: request.config = config if audio is not None: @@ -454,7 +454,6 @@ def long_running_recognize( This corresponds to the ``audio`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -489,10 +488,8 @@ def long_running_recognize( # there are no flattened fields. if not isinstance(request, cloud_speech.LongRunningRecognizeRequest): request = cloud_speech.LongRunningRecognizeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if config is not None: request.config = config if audio is not None: diff --git a/google/cloud/speech_v1/services/speech/transports/__init__.py b/google/cloud/speech_v1/services/speech/transports/__init__.py index d7ef55b1..9672a67d 100644 --- a/google/cloud/speech_v1/services/speech/transports/__init__.py +++ b/google/cloud/speech_v1/services/speech/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/speech_v1/services/speech/transports/base.py b/google/cloud/speech_v1/services/speech/transports/base.py index 2bbcab4b..a2e0b4de 100644 --- a/google/cloud/speech_v1/services/speech/transports/base.py +++ b/google/cloud/speech_v1/services/speech/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.speech_v1.types import cloud_speech -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,27 +36,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SpeechTransport(abc.ABC): """Abstract transport class for Speech.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "speech.googleapis.com" + def __init__( self, *, - host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -66,7 +79,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -80,29 +93,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -113,7 +173,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=5000.0, ), @@ -132,7 +193,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=5000.0, ), @@ -149,11 +211,10 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def recognize( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech.RecognizeRequest], - typing.Union[ - cloud_speech.RecognizeResponse, - typing.Awaitable[cloud_speech.RecognizeResponse], + Union[ + cloud_speech.RecognizeResponse, Awaitable[cloud_speech.RecognizeResponse] ], ]: raise NotImplementedError() @@ -161,20 +222,20 @@ def recognize( @property def long_running_recognize( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech.LongRunningRecognizeRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def streaming_recognize( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech.StreamingRecognizeRequest], - typing.Union[ + Union[ cloud_speech.StreamingRecognizeResponse, - typing.Awaitable[cloud_speech.StreamingRecognizeResponse], + Awaitable[cloud_speech.StreamingRecognizeResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/speech_v1/services/speech/transports/grpc.py b/google/cloud/speech_v1/services/speech/transports/grpc.py index 62e076df..4c3d9b39 100644 --- a/google/cloud/speech_v1/services/speech/transports/grpc.py +++ b/google/cloud/speech_v1/services/speech/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.speech_v1.types import cloud_speech -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import SpeechTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -177,7 +175,7 @@ def __init__( def create_channel( cls, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -208,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -268,7 +268,7 @@ def recognize( @property def long_running_recognize( self, - ) -> Callable[[cloud_speech.LongRunningRecognizeRequest], operations.Operation]: + ) -> Callable[[cloud_speech.LongRunningRecognizeRequest], operations_pb2.Operation]: r"""Return a callable for the long running recognize method over gRPC. Performs asynchronous speech recognition: receive results via @@ -292,7 +292,7 @@ def long_running_recognize( self._stubs["long_running_recognize"] = self.grpc_channel.unary_unary( "/google.cloud.speech.v1.Speech/LongRunningRecognize", request_serializer=cloud_speech.LongRunningRecognizeRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["long_running_recognize"] diff --git a/google/cloud/speech_v1/services/speech/transports/grpc_asyncio.py b/google/cloud/speech_v1/services/speech/transports/grpc_asyncio.py index 95b533d9..a41c03f7 100644 --- a/google/cloud/speech_v1/services/speech/transports/grpc_asyncio.py +++ b/google/cloud/speech_v1/services/speech/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.speech_v1.types import cloud_speech -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import SpeechTransport, DEFAULT_CLIENT_INFO from .grpc import SpeechGrpcTransport @@ -55,7 +52,7 @@ class SpeechGrpcAsyncIOTransport(SpeechTransport): def create_channel( cls, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -277,7 +276,7 @@ def recognize( def long_running_recognize( self, ) -> Callable[ - [cloud_speech.LongRunningRecognizeRequest], Awaitable[operations.Operation] + [cloud_speech.LongRunningRecognizeRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the long running recognize method over gRPC. @@ -302,7 +301,7 @@ def long_running_recognize( self._stubs["long_running_recognize"] = self.grpc_channel.unary_unary( "/google.cloud.speech.v1.Speech/LongRunningRecognize", request_serializer=cloud_speech.LongRunningRecognizeRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["long_running_recognize"] diff --git a/google/cloud/speech_v1/types/__init__.py b/google/cloud/speech_v1/types/__init__.py index a08e2564..31843103 100644 --- a/google/cloud/speech_v1/types/__init__.py +++ b/google/cloud/speech_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .cloud_speech import ( LongRunningRecognizeMetadata, LongRunningRecognizeRequest, diff --git a/google/cloud/speech_v1/types/cloud_speech.py b/google/cloud/speech_v1/types/cloud_speech.py index a2a8401b..f1420b46 100644 --- a/google/cloud/speech_v1/types/cloud_speech.py +++ b/google/cloud/speech_v1/types/cloud_speech.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -61,7 +58,6 @@ class RecognizeRequest(proto.Message): """ config = proto.Field(proto.MESSAGE, number=1, message="RecognitionConfig",) - audio = proto.Field(proto.MESSAGE, number=2, message="RecognitionAudio",) @@ -79,7 +75,6 @@ class LongRunningRecognizeRequest(proto.Message): """ config = proto.Field(proto.MESSAGE, number=1, message="RecognitionConfig",) - audio = proto.Field(proto.MESSAGE, number=2, message="RecognitionAudio",) @@ -116,8 +111,7 @@ class StreamingRecognizeRequest(proto.Message): oneof="streaming_request", message="StreamingRecognitionConfig", ) - - audio_content = proto.Field(proto.BYTES, number=2, oneof="streaming_request") + audio_content = proto.Field(proto.BYTES, number=2, oneof="streaming_request",) class StreamingRecognitionConfig(proto.Message): @@ -152,10 +146,8 @@ class StreamingRecognitionConfig(proto.Message): """ config = proto.Field(proto.MESSAGE, number=1, message="RecognitionConfig",) - - single_utterance = proto.Field(proto.BOOL, number=2) - - interim_results = proto.Field(proto.BOOL, number=3) + single_utterance = proto.Field(proto.BOOL, number=2,) + interim_results = proto.Field(proto.BOOL, number=3,) class RecognitionConfig(proto.Message): @@ -339,41 +331,27 @@ class AudioEncoding(proto.Enum): SPEEX_WITH_HEADER_BYTE = 7 encoding = proto.Field(proto.ENUM, number=1, enum=AudioEncoding,) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - - audio_channel_count = proto.Field(proto.INT32, number=7) - - enable_separate_recognition_per_channel = proto.Field(proto.BOOL, number=12) - - language_code = proto.Field(proto.STRING, number=3) - - max_alternatives = proto.Field(proto.INT32, number=4) - - profanity_filter = proto.Field(proto.BOOL, number=5) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) + audio_channel_count = proto.Field(proto.INT32, number=7,) + enable_separate_recognition_per_channel = proto.Field(proto.BOOL, number=12,) + language_code = proto.Field(proto.STRING, number=3,) + max_alternatives = proto.Field(proto.INT32, number=4,) + profanity_filter = proto.Field(proto.BOOL, number=5,) speech_contexts = proto.RepeatedField( proto.MESSAGE, number=6, message="SpeechContext", ) - - enable_word_time_offsets = proto.Field(proto.BOOL, number=8) - - enable_automatic_punctuation = proto.Field(proto.BOOL, number=11) - + enable_word_time_offsets = proto.Field(proto.BOOL, number=8,) + enable_automatic_punctuation = proto.Field(proto.BOOL, number=11,) diarization_config = proto.Field( proto.MESSAGE, number=19, message="SpeakerDiarizationConfig", ) - metadata = proto.Field(proto.MESSAGE, number=9, message="RecognitionMetadata",) - - model = proto.Field(proto.STRING, number=13) - - use_enhanced = proto.Field(proto.BOOL, number=14) + model = proto.Field(proto.STRING, number=13,) + use_enhanced = proto.Field(proto.BOOL, number=14,) class SpeakerDiarizationConfig(proto.Message): r"""Config to enable speaker diarization. - Attributes: enable_speaker_diarization (bool): If 'true', enables speaker detection for each recognized @@ -395,18 +373,14 @@ class SpeakerDiarizationConfig(proto.Message): Unused. """ - enable_speaker_diarization = proto.Field(proto.BOOL, number=1) - - min_speaker_count = proto.Field(proto.INT32, number=2) - - max_speaker_count = proto.Field(proto.INT32, number=3) - - speaker_tag = proto.Field(proto.INT32, number=5) + enable_speaker_diarization = proto.Field(proto.BOOL, number=1,) + min_speaker_count = proto.Field(proto.INT32, number=2,) + max_speaker_count = proto.Field(proto.INT32, number=3,) + speaker_tag = proto.Field(proto.INT32, number=5,) class RecognitionMetadata(proto.Message): r"""Description of audio data to be recognized. - Attributes: interaction_type (google.cloud.speech_v1.types.RecognitionMetadata.InteractionType): The use case most closely describing the @@ -483,20 +457,13 @@ class RecordingDeviceType(proto.Enum): OTHER_INDOOR_DEVICE = 6 interaction_type = proto.Field(proto.ENUM, number=1, enum=InteractionType,) - - industry_naics_code_of_audio = proto.Field(proto.UINT32, number=3) - + industry_naics_code_of_audio = proto.Field(proto.UINT32, number=3,) microphone_distance = proto.Field(proto.ENUM, number=4, enum=MicrophoneDistance,) - original_media_type = proto.Field(proto.ENUM, number=5, enum=OriginalMediaType,) - recording_device_type = proto.Field(proto.ENUM, number=6, enum=RecordingDeviceType,) - - recording_device_name = proto.Field(proto.STRING, number=7) - - original_mime_type = proto.Field(proto.STRING, number=8) - - audio_topic = proto.Field(proto.STRING, number=10) + recording_device_name = proto.Field(proto.STRING, number=7,) + original_mime_type = proto.Field(proto.STRING, number=8,) + audio_topic = proto.Field(proto.STRING, number=10,) class SpeechContext(proto.Message): @@ -522,7 +489,7 @@ class SpeechContext(proto.Message): months. """ - phrases = proto.RepeatedField(proto.STRING, number=1) + phrases = proto.RepeatedField(proto.STRING, number=1,) class RecognitionAudio(proto.Message): @@ -551,9 +518,8 @@ class RecognitionAudio(proto.Message): URIs `__. """ - content = proto.Field(proto.BYTES, number=1, oneof="audio_source") - - uri = proto.Field(proto.STRING, number=2, oneof="audio_source") + content = proto.Field(proto.BYTES, number=1, oneof="audio_source",) + uri = proto.Field(proto.STRING, number=2, oneof="audio_source",) class RecognizeResponse(proto.Message): @@ -608,12 +574,10 @@ class LongRunningRecognizeMetadata(proto.Message): Time of the most recent processing update. """ - progress_percent = proto.Field(proto.INT32, number=1) - - start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - + progress_percent = proto.Field(proto.INT32, number=1,) + start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) last_update_time = proto.Field( - proto.MESSAGE, number=3, message=timestamp.Timestamp, + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, ) @@ -691,12 +655,10 @@ class SpeechEventType(proto.Enum): SPEECH_EVENT_UNSPECIFIED = 0 END_OF_SINGLE_UTTERANCE = 1 - error = proto.Field(proto.MESSAGE, number=1, message=status.Status,) - + error = proto.Field(proto.MESSAGE, number=1, message=status_pb2.Status,) results = proto.RepeatedField( proto.MESSAGE, number=2, message="StreamingRecognitionResult", ) - speech_event_type = proto.Field(proto.ENUM, number=4, enum=SpeechEventType,) @@ -744,16 +706,13 @@ class StreamingRecognitionResult(proto.Message): alternatives = proto.RepeatedField( proto.MESSAGE, number=1, message="SpeechRecognitionAlternative", ) - - is_final = proto.Field(proto.BOOL, number=2) - - stability = proto.Field(proto.FLOAT, number=3) - - result_end_time = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) - - channel_tag = proto.Field(proto.INT32, number=5) - - language_code = proto.Field(proto.STRING, number=6) + is_final = proto.Field(proto.BOOL, number=2,) + stability = proto.Field(proto.FLOAT, number=3,) + result_end_time = proto.Field( + proto.MESSAGE, number=4, message=duration_pb2.Duration, + ) + channel_tag = proto.Field(proto.INT32, number=5,) + language_code = proto.Field(proto.STRING, number=6,) class SpeechRecognitionResult(proto.Message): @@ -777,13 +736,11 @@ class SpeechRecognitionResult(proto.Message): alternatives = proto.RepeatedField( proto.MESSAGE, number=1, message="SpeechRecognitionAlternative", ) - - channel_tag = proto.Field(proto.INT32, number=2) + channel_tag = proto.Field(proto.INT32, number=2,) class SpeechRecognitionAlternative(proto.Message): r"""Alternative hypotheses (a.k.a. n-best list). - Attributes: transcript (str): Transcript text representing the words that @@ -803,16 +760,13 @@ class SpeechRecognitionAlternative(proto.Message): will see all the words from the beginning of the audio. """ - transcript = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) - + transcript = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) words = proto.RepeatedField(proto.MESSAGE, number=3, message="WordInfo",) class WordInfo(proto.Message): r"""Word-specific information for recognized words. - Attributes: start_time (google.protobuf.duration_pb2.Duration): Time offset relative to the beginning of the audio, and @@ -838,13 +792,10 @@ class WordInfo(proto.Message): alternative. """ - start_time = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) - - end_time = proto.Field(proto.MESSAGE, number=2, message=duration.Duration,) - - word = proto.Field(proto.STRING, number=3) - - speaker_tag = proto.Field(proto.INT32, number=5) + start_time = proto.Field(proto.MESSAGE, number=1, message=duration_pb2.Duration,) + end_time = proto.Field(proto.MESSAGE, number=2, message=duration_pb2.Duration,) + word = proto.Field(proto.STRING, number=3,) + speaker_tag = proto.Field(proto.INT32, number=5,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/speech_v1p1beta1/__init__.py b/google/cloud/speech_v1p1beta1/__init__.py index a45dedd4..4b6f5cbe 100644 --- a/google/cloud/speech_v1p1beta1/__init__.py +++ b/google/cloud/speech_v1p1beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,7 +15,10 @@ # from .services.adaptation import AdaptationClient +from .services.adaptation import AdaptationAsyncClient from .services.speech import SpeechClient +from .services.speech import SpeechAsyncClient + from .types.cloud_speech import LongRunningRecognizeMetadata from .types.cloud_speech import LongRunningRecognizeRequest from .types.cloud_speech import LongRunningRecognizeResponse @@ -51,7 +53,6 @@ from .types.resource import PhraseSet from .types.resource import SpeechAdaptation - from google.cloud.speech_v1.helpers import SpeechHelpers @@ -60,6 +61,9 @@ class SpeechClient(SpeechHelpers, SpeechClient): __all__ = ( + "AdaptationAsyncClient", + "SpeechAsyncClient", + "AdaptationClient", "CreateCustomClassRequest", "CreatePhraseSetRequest", "CustomClass", @@ -94,5 +98,4 @@ class SpeechClient(SpeechHelpers, SpeechClient): "UpdateCustomClassRequest", "UpdatePhraseSetRequest", "WordInfo", - "AdaptationClient", ) diff --git a/google/cloud/speech_v1p1beta1/gapic_metadata.json b/google/cloud/speech_v1p1beta1/gapic_metadata.json new file mode 100644 index 00000000..3561c102 --- /dev/null +++ b/google/cloud/speech_v1p1beta1/gapic_metadata.json @@ -0,0 +1,167 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.speech_v1p1beta1", + "protoPackage": "google.cloud.speech.v1p1beta1", + "schema": "1.0", + "services": { + "Adaptation": { + "clients": { + "grpc": { + "libraryClient": "AdaptationClient", + "rpcs": { + "CreateCustomClass": { + "methods": [ + "create_custom_class" + ] + }, + "CreatePhraseSet": { + "methods": [ + "create_phrase_set" + ] + }, + "DeleteCustomClass": { + "methods": [ + "delete_custom_class" + ] + }, + "DeletePhraseSet": { + "methods": [ + "delete_phrase_set" + ] + }, + "GetCustomClass": { + "methods": [ + "get_custom_class" + ] + }, + "GetPhraseSet": { + "methods": [ + "get_phrase_set" + ] + }, + "ListCustomClasses": { + "methods": [ + "list_custom_classes" + ] + }, + "ListPhraseSet": { + "methods": [ + "list_phrase_set" + ] + }, + "UpdateCustomClass": { + "methods": [ + "update_custom_class" + ] + }, + "UpdatePhraseSet": { + "methods": [ + "update_phrase_set" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AdaptationAsyncClient", + "rpcs": { + "CreateCustomClass": { + "methods": [ + "create_custom_class" + ] + }, + "CreatePhraseSet": { + "methods": [ + "create_phrase_set" + ] + }, + "DeleteCustomClass": { + "methods": [ + "delete_custom_class" + ] + }, + "DeletePhraseSet": { + "methods": [ + "delete_phrase_set" + ] + }, + "GetCustomClass": { + "methods": [ + "get_custom_class" + ] + }, + "GetPhraseSet": { + "methods": [ + "get_phrase_set" + ] + }, + "ListCustomClasses": { + "methods": [ + "list_custom_classes" + ] + }, + "ListPhraseSet": { + "methods": [ + "list_phrase_set" + ] + }, + "UpdateCustomClass": { + "methods": [ + "update_custom_class" + ] + }, + "UpdatePhraseSet": { + "methods": [ + "update_phrase_set" + ] + } + } + } + } + }, + "Speech": { + "clients": { + "grpc": { + "libraryClient": "SpeechClient", + "rpcs": { + "LongRunningRecognize": { + "methods": [ + "long_running_recognize" + ] + }, + "Recognize": { + "methods": [ + "recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "streaming_recognize" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SpeechAsyncClient", + "rpcs": { + "LongRunningRecognize": { + "methods": [ + "long_running_recognize" + ] + }, + "Recognize": { + "methods": [ + "recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "streaming_recognize" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/speech_v1p1beta1/services/__init__.py b/google/cloud/speech_v1p1beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/speech_v1p1beta1/services/__init__.py +++ b/google/cloud/speech_v1p1beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/__init__.py b/google/cloud/speech_v1p1beta1/services/adaptation/__init__.py index 6de88b81..00ce7ae3 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/__init__.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AdaptationClient from .async_client import AdaptationAsyncClient diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py b/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py index 42ff88d1..7c17db73 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,17 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.speech_v1p1beta1.services.adaptation import pagers from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import AdaptationTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AdaptationGrpcAsyncIOTransport from .client import AdaptationClient @@ -50,25 +47,20 @@ class AdaptationAsyncClient: parse_custom_class_path = staticmethod(AdaptationClient.parse_custom_class_path) phrase_set_path = staticmethod(AdaptationClient.phrase_set_path) parse_phrase_set_path = staticmethod(AdaptationClient.parse_phrase_set_path) - common_billing_account_path = staticmethod( AdaptationClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( AdaptationClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AdaptationClient.common_folder_path) parse_common_folder_path = staticmethod(AdaptationClient.parse_common_folder_path) - common_organization_path = staticmethod(AdaptationClient.common_organization_path) parse_common_organization_path = staticmethod( AdaptationClient.parse_common_organization_path ) - common_project_path = staticmethod(AdaptationClient.common_project_path) parse_common_project_path = staticmethod(AdaptationClient.parse_common_project_path) - common_location_path = staticmethod(AdaptationClient.common_location_path) parse_common_location_path = staticmethod( AdaptationClient.parse_common_location_path @@ -76,7 +68,8 @@ class AdaptationAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -91,7 +84,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -108,7 +101,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AdaptationTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AdaptationTransport: The transport used by the client instance. @@ -122,12 +115,12 @@ def transport(self) -> AdaptationTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AdaptationTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the adaptation client. + """Instantiates the adaptation client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -159,7 +152,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AdaptationClient( credentials=credentials, transport=transport, @@ -210,7 +202,6 @@ async def create_phrase_set( This corresponds to the ``phrase_set_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -238,7 +229,6 @@ async def create_phrase_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if phrase_set is not None: @@ -289,7 +279,6 @@ async def get_phrase_set( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -317,7 +306,6 @@ async def get_phrase_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -364,7 +352,6 @@ async def list_phrase_set( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -394,7 +381,6 @@ async def list_phrase_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -429,7 +415,7 @@ async def update_phrase_set( request: cloud_speech_adaptation.UpdatePhraseSetRequest = None, *, phrase_set: resource.PhraseSet = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -455,7 +441,6 @@ async def update_phrase_set( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -483,7 +468,6 @@ async def update_phrase_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if phrase_set is not None: request.phrase_set = phrase_set if update_mask is not None: @@ -533,7 +517,6 @@ async def delete_phrase_set( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -554,7 +537,6 @@ async def delete_phrase_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -617,7 +599,6 @@ async def create_custom_class( This corresponds to the ``custom_class_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -649,7 +630,6 @@ async def create_custom_class( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if custom_class is not None: @@ -700,7 +680,6 @@ async def get_custom_class( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -732,7 +711,6 @@ async def get_custom_class( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -779,7 +757,6 @@ async def list_custom_classes( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -809,7 +786,6 @@ async def list_custom_classes( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -844,7 +820,7 @@ async def update_custom_class( request: cloud_speech_adaptation.UpdateCustomClassRequest = None, *, custom_class: resource.CustomClass = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -870,7 +846,6 @@ async def update_custom_class( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -902,7 +877,6 @@ async def update_custom_class( # If we have keyword arguments corresponding to fields on the # request, apply these. - if custom_class is not None: request.custom_class = custom_class if update_mask is not None: @@ -953,7 +927,6 @@ async def delete_custom_class( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -974,7 +947,6 @@ async def delete_custom_class( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/client.py b/google/cloud/speech_v1p1beta1/services/adaptation/client.py index 07ef9aa5..29dd77f2 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/client.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,8 +33,7 @@ from google.cloud.speech_v1p1beta1.services.adaptation import pagers from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import AdaptationTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdaptationGrpcTransport from .transports.grpc_asyncio import AdaptationGrpcAsyncIOTransport @@ -55,7 +52,7 @@ class AdaptationClientMeta(type): _transport_registry["grpc_asyncio"] = AdaptationGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AdaptationTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -78,7 +75,8 @@ class AdaptationClient(metaclass=AdaptationClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -112,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -129,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -148,23 +147,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AdaptationTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AdaptationTransport: The transport used by the client instance. + AdaptationTransport: The transport used by the client + instance. """ return self._transport @staticmethod def custom_class_path(project: str, location: str, custom_class: str,) -> str: - """Return a fully-qualified custom_class string.""" + """Returns a fully-qualified custom_class string.""" return "projects/{project}/locations/{location}/customClasses/{custom_class}".format( project=project, location=location, custom_class=custom_class, ) @staticmethod def parse_custom_class_path(path: str) -> Dict[str, str]: - """Parse a custom_class path into its component segments.""" + """Parses a custom_class path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/customClasses/(?P.+?)$", path, @@ -173,14 +173,14 @@ def parse_custom_class_path(path: str) -> Dict[str, str]: @staticmethod def phrase_set_path(project: str, location: str, phrase_set: str,) -> str: - """Return a fully-qualified phrase_set string.""" + """Returns a fully-qualified phrase_set string.""" return "projects/{project}/locations/{location}/phraseSets/{phrase_set}".format( project=project, location=location, phrase_set=phrase_set, ) @staticmethod def parse_phrase_set_path(path: str) -> Dict[str, str]: - """Parse a phrase_set path into its component segments.""" + """Parses a phrase_set path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/phraseSets/(?P.+?)$", path, @@ -189,7 +189,7 @@ def parse_phrase_set_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -202,7 +202,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -213,7 +213,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -224,7 +224,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -235,7 +235,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -249,12 +249,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AdaptationTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the adaptation client. + """Instantiates the adaptation client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -309,9 +309,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -323,12 +324,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -343,8 +346,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -402,7 +405,6 @@ def create_phrase_set( This corresponds to the ``phrase_set_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -432,10 +434,8 @@ def create_phrase_set( # there are no flattened fields. if not isinstance(request, cloud_speech_adaptation.CreatePhraseSetRequest): request = cloud_speech_adaptation.CreatePhraseSetRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if phrase_set is not None: @@ -482,7 +482,6 @@ def get_phrase_set( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -512,10 +511,8 @@ def get_phrase_set( # there are no flattened fields. if not isinstance(request, cloud_speech_adaptation.GetPhraseSetRequest): request = cloud_speech_adaptation.GetPhraseSetRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -558,7 +555,6 @@ def list_phrase_set( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -590,10 +586,8 @@ def list_phrase_set( # there are no flattened fields. if not isinstance(request, cloud_speech_adaptation.ListPhraseSetRequest): request = cloud_speech_adaptation.ListPhraseSetRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -624,7 +618,7 @@ def update_phrase_set( request: cloud_speech_adaptation.UpdatePhraseSetRequest = None, *, phrase_set: resource.PhraseSet = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -650,7 +644,6 @@ def update_phrase_set( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -680,10 +673,8 @@ def update_phrase_set( # there are no flattened fields. if not isinstance(request, cloud_speech_adaptation.UpdatePhraseSetRequest): request = cloud_speech_adaptation.UpdatePhraseSetRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if phrase_set is not None: request.phrase_set = phrase_set if update_mask is not None: @@ -729,7 +720,6 @@ def delete_phrase_set( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -752,10 +742,8 @@ def delete_phrase_set( # there are no flattened fields. if not isinstance(request, cloud_speech_adaptation.DeletePhraseSetRequest): request = cloud_speech_adaptation.DeletePhraseSetRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -814,7 +802,6 @@ def create_custom_class( This corresponds to the ``custom_class_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -848,10 +835,8 @@ def create_custom_class( # there are no flattened fields. if not isinstance(request, cloud_speech_adaptation.CreateCustomClassRequest): request = cloud_speech_adaptation.CreateCustomClassRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if custom_class is not None: @@ -898,7 +883,6 @@ def get_custom_class( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -932,10 +916,8 @@ def get_custom_class( # there are no flattened fields. if not isinstance(request, cloud_speech_adaptation.GetCustomClassRequest): request = cloud_speech_adaptation.GetCustomClassRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -978,7 +960,6 @@ def list_custom_classes( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1010,10 +991,8 @@ def list_custom_classes( # there are no flattened fields. if not isinstance(request, cloud_speech_adaptation.ListCustomClassesRequest): request = cloud_speech_adaptation.ListCustomClassesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1044,7 +1023,7 @@ def update_custom_class( request: cloud_speech_adaptation.UpdateCustomClassRequest = None, *, custom_class: resource.CustomClass = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1070,7 +1049,6 @@ def update_custom_class( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1104,10 +1082,8 @@ def update_custom_class( # there are no flattened fields. if not isinstance(request, cloud_speech_adaptation.UpdateCustomClassRequest): request = cloud_speech_adaptation.UpdateCustomClassRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if custom_class is not None: request.custom_class = custom_class if update_mask is not None: @@ -1154,7 +1130,6 @@ def delete_custom_class( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1177,10 +1152,8 @@ def delete_custom_class( # there are no flattened fields. if not isinstance(request, cloud_speech_adaptation.DeleteCustomClassRequest): request = cloud_speech_adaptation.DeleteCustomClassRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/pagers.py b/google/cloud/speech_v1p1beta1/services/adaptation/pagers.py index a93a47e7..d1df3c26 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/pagers.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -250,7 +248,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/transports/__init__.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/__init__.py index b9694a54..6ca6bbe1 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/transports/__init__.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py index a6f3a241..a02a4ebb 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,27 +36,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AdaptationTransport(abc.ABC): """Abstract transport class for Adaptation.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "speech.googleapis.com" + def __init__( self, *, - host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -66,7 +79,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -80,29 +93,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -141,29 +201,29 @@ def _prep_wrapped_messages(self, client_info): @property def create_phrase_set( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech_adaptation.CreatePhraseSetRequest], - typing.Union[resource.PhraseSet, typing.Awaitable[resource.PhraseSet]], + Union[resource.PhraseSet, Awaitable[resource.PhraseSet]], ]: raise NotImplementedError() @property def get_phrase_set( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech_adaptation.GetPhraseSetRequest], - typing.Union[resource.PhraseSet, typing.Awaitable[resource.PhraseSet]], + Union[resource.PhraseSet, Awaitable[resource.PhraseSet]], ]: raise NotImplementedError() @property def list_phrase_set( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech_adaptation.ListPhraseSetRequest], - typing.Union[ + Union[ cloud_speech_adaptation.ListPhraseSetResponse, - typing.Awaitable[cloud_speech_adaptation.ListPhraseSetResponse], + Awaitable[cloud_speech_adaptation.ListPhraseSetResponse], ], ]: raise NotImplementedError() @@ -171,47 +231,47 @@ def list_phrase_set( @property def update_phrase_set( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech_adaptation.UpdatePhraseSetRequest], - typing.Union[resource.PhraseSet, typing.Awaitable[resource.PhraseSet]], + Union[resource.PhraseSet, Awaitable[resource.PhraseSet]], ]: raise NotImplementedError() @property def delete_phrase_set( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech_adaptation.DeletePhraseSetRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def create_custom_class( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech_adaptation.CreateCustomClassRequest], - typing.Union[resource.CustomClass, typing.Awaitable[resource.CustomClass]], + Union[resource.CustomClass, Awaitable[resource.CustomClass]], ]: raise NotImplementedError() @property def get_custom_class( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech_adaptation.GetCustomClassRequest], - typing.Union[resource.CustomClass, typing.Awaitable[resource.CustomClass]], + Union[resource.CustomClass, Awaitable[resource.CustomClass]], ]: raise NotImplementedError() @property def list_custom_classes( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech_adaptation.ListCustomClassesRequest], - typing.Union[ + Union[ cloud_speech_adaptation.ListCustomClassesResponse, - typing.Awaitable[cloud_speech_adaptation.ListCustomClassesResponse], + Awaitable[cloud_speech_adaptation.ListCustomClassesResponse], ], ]: raise NotImplementedError() @@ -219,18 +279,18 @@ def list_custom_classes( @property def update_custom_class( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech_adaptation.UpdateCustomClassRequest], - typing.Union[resource.CustomClass, typing.Awaitable[resource.CustomClass]], + Union[resource.CustomClass, Awaitable[resource.CustomClass]], ]: raise NotImplementedError() @property def delete_custom_class( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech_adaptation.DeleteCustomClassRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py index b7e0be71..eee794ae 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import AdaptationTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -176,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -207,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -336,7 +336,7 @@ def update_phrase_set( @property def delete_phrase_set( self, - ) -> Callable[[cloud_speech_adaptation.DeletePhraseSetRequest], empty.Empty]: + ) -> Callable[[cloud_speech_adaptation.DeletePhraseSetRequest], empty_pb2.Empty]: r"""Return a callable for the delete phrase set method over gRPC. Delete a phrase set. @@ -355,7 +355,7 @@ def delete_phrase_set( self._stubs["delete_phrase_set"] = self.grpc_channel.unary_unary( "/google.cloud.speech.v1p1beta1.Adaptation/DeletePhraseSet", request_serializer=cloud_speech_adaptation.DeletePhraseSetRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_phrase_set"] @@ -475,7 +475,7 @@ def update_custom_class( @property def delete_custom_class( self, - ) -> Callable[[cloud_speech_adaptation.DeleteCustomClassRequest], empty.Empty]: + ) -> Callable[[cloud_speech_adaptation.DeleteCustomClassRequest], empty_pb2.Empty]: r"""Return a callable for the delete custom class method over gRPC. Delete a custom class. @@ -494,7 +494,7 @@ def delete_custom_class( self._stubs["delete_custom_class"] = self.grpc_channel.unary_unary( "/google.cloud.speech.v1p1beta1.Adaptation/DeleteCustomClass", request_serializer=cloud_speech_adaptation.DeleteCustomClassRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_custom_class"] diff --git a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py index b8da6c81..314ba063 100644 --- a/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py +++ b/google/cloud/speech_v1p1beta1/services/adaptation/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import AdaptationTransport, DEFAULT_CLIENT_INFO from .grpc import AdaptationGrpcTransport @@ -55,7 +52,7 @@ class AdaptationGrpcAsyncIOTransport(AdaptationTransport): def create_channel( cls, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -347,7 +346,7 @@ def update_phrase_set( def delete_phrase_set( self, ) -> Callable[ - [cloud_speech_adaptation.DeletePhraseSetRequest], Awaitable[empty.Empty] + [cloud_speech_adaptation.DeletePhraseSetRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete phrase set method over gRPC. @@ -367,7 +366,7 @@ def delete_phrase_set( self._stubs["delete_phrase_set"] = self.grpc_channel.unary_unary( "/google.cloud.speech.v1p1beta1.Adaptation/DeletePhraseSet", request_serializer=cloud_speech_adaptation.DeletePhraseSetRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_phrase_set"] @@ -490,7 +489,7 @@ def update_custom_class( def delete_custom_class( self, ) -> Callable[ - [cloud_speech_adaptation.DeleteCustomClassRequest], Awaitable[empty.Empty] + [cloud_speech_adaptation.DeleteCustomClassRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete custom class method over gRPC. @@ -510,7 +509,7 @@ def delete_custom_class( self._stubs["delete_custom_class"] = self.grpc_channel.unary_unary( "/google.cloud.speech.v1p1beta1.Adaptation/DeleteCustomClass", request_serializer=cloud_speech_adaptation.DeleteCustomClassRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_custom_class"] diff --git a/google/cloud/speech_v1p1beta1/services/speech/__init__.py b/google/cloud/speech_v1p1beta1/services/speech/__init__.py index 72f816da..5a359701 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/__init__.py +++ b/google/cloud/speech_v1p1beta1/services/speech/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SpeechClient from .async_client import SpeechAsyncClient diff --git a/google/cloud/speech_v1p1beta1/services/speech/async_client.py b/google/cloud/speech_v1p1beta1/services/speech/async_client.py index 41200ed8..2a463476 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/async_client.py +++ b/google/cloud/speech_v1p1beta1/services/speech/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -31,17 +29,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SpeechTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SpeechGrpcAsyncIOTransport from .client import SpeechClient @@ -59,29 +56,25 @@ class SpeechAsyncClient: parse_custom_class_path = staticmethod(SpeechClient.parse_custom_class_path) phrase_set_path = staticmethod(SpeechClient.phrase_set_path) parse_phrase_set_path = staticmethod(SpeechClient.parse_phrase_set_path) - common_billing_account_path = staticmethod(SpeechClient.common_billing_account_path) parse_common_billing_account_path = staticmethod( SpeechClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SpeechClient.common_folder_path) parse_common_folder_path = staticmethod(SpeechClient.parse_common_folder_path) - common_organization_path = staticmethod(SpeechClient.common_organization_path) parse_common_organization_path = staticmethod( SpeechClient.parse_common_organization_path ) - common_project_path = staticmethod(SpeechClient.common_project_path) parse_common_project_path = staticmethod(SpeechClient.parse_common_project_path) - common_location_path = staticmethod(SpeechClient.common_location_path) parse_common_location_path = staticmethod(SpeechClient.parse_common_location_path) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -96,7 +89,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -113,7 +106,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SpeechTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SpeechTransport: The transport used by the client instance. @@ -127,12 +120,12 @@ def transport(self) -> SpeechTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SpeechTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the speech client. + """Instantiates the speech client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -164,7 +157,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SpeechClient( credentials=credentials, transport=transport, @@ -204,7 +196,6 @@ async def recognize( This corresponds to the ``audio`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -232,7 +223,6 @@ async def recognize( # If we have keyword arguments corresponding to fields on the # request, apply these. - if config is not None: request.config = config if audio is not None: @@ -247,7 +237,8 @@ async def recognize( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=5000.0, ), @@ -297,7 +288,6 @@ async def long_running_recognize( This corresponds to the ``audio`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -330,7 +320,6 @@ async def long_running_recognize( # If we have keyword arguments corresponding to fields on the # request, apply these. - if config is not None: request.config = config if audio is not None: @@ -459,7 +448,8 @@ def streaming_recognize( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=5000.0, ), diff --git a/google/cloud/speech_v1p1beta1/services/speech/client.py b/google/cloud/speech_v1p1beta1/services/speech/client.py index 382b448e..ed5ef35e 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/client.py +++ b/google/cloud/speech_v1p1beta1/services/speech/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -33,10 +31,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -45,8 +43,7 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SpeechTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SpeechGrpcTransport from .transports.grpc_asyncio import SpeechGrpcAsyncIOTransport @@ -65,7 +62,7 @@ class SpeechClientMeta(type): _transport_registry["grpc_asyncio"] = SpeechGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SpeechTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -88,7 +85,8 @@ class SpeechClient(metaclass=SpeechClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -122,7 +120,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -139,7 +138,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -158,23 +157,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SpeechTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SpeechTransport: The transport used by the client instance. + SpeechTransport: The transport used by the client + instance. """ return self._transport @staticmethod def custom_class_path(project: str, location: str, custom_class: str,) -> str: - """Return a fully-qualified custom_class string.""" + """Returns a fully-qualified custom_class string.""" return "projects/{project}/locations/{location}/customClasses/{custom_class}".format( project=project, location=location, custom_class=custom_class, ) @staticmethod def parse_custom_class_path(path: str) -> Dict[str, str]: - """Parse a custom_class path into its component segments.""" + """Parses a custom_class path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/customClasses/(?P.+?)$", path, @@ -183,14 +183,14 @@ def parse_custom_class_path(path: str) -> Dict[str, str]: @staticmethod def phrase_set_path(project: str, location: str, phrase_set: str,) -> str: - """Return a fully-qualified phrase_set string.""" + """Returns a fully-qualified phrase_set string.""" return "projects/{project}/locations/{location}/phraseSets/{phrase_set}".format( project=project, location=location, phrase_set=phrase_set, ) @staticmethod def parse_phrase_set_path(path: str) -> Dict[str, str]: - """Parse a phrase_set path into its component segments.""" + """Parses a phrase_set path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/phraseSets/(?P.+?)$", path, @@ -199,7 +199,7 @@ def parse_phrase_set_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -212,7 +212,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -223,7 +223,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -234,7 +234,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -245,7 +245,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -259,12 +259,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SpeechTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the speech client. + """Instantiates the speech client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -319,9 +319,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -333,12 +334,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -353,8 +356,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -401,7 +404,6 @@ def recognize( This corresponds to the ``audio`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -431,10 +433,8 @@ def recognize( # there are no flattened fields. if not isinstance(request, cloud_speech.RecognizeRequest): request = cloud_speech.RecognizeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if config is not None: request.config = config if audio is not None: @@ -486,7 +486,6 @@ def long_running_recognize( This corresponds to the ``audio`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -521,10 +520,8 @@ def long_running_recognize( # there are no flattened fields. if not isinstance(request, cloud_speech.LongRunningRecognizeRequest): request = cloud_speech.LongRunningRecognizeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if config is not None: request.config = config if audio is not None: diff --git a/google/cloud/speech_v1p1beta1/services/speech/transports/__init__.py b/google/cloud/speech_v1p1beta1/services/speech/transports/__init__.py index d7ef55b1..9672a67d 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/transports/__init__.py +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/speech_v1p1beta1/services/speech/transports/base.py b/google/cloud/speech_v1p1beta1/services/speech/transports/base.py index 6c4e8d6f..9cda1777 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/transports/base.py +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,27 +36,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SpeechTransport(abc.ABC): """Abstract transport class for Speech.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "speech.googleapis.com" + def __init__( self, *, - host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -66,7 +79,7 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): @@ -80,29 +93,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -113,7 +173,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=5000.0, ), @@ -132,7 +193,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=5000.0, ), @@ -149,11 +211,10 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def recognize( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech.RecognizeRequest], - typing.Union[ - cloud_speech.RecognizeResponse, - typing.Awaitable[cloud_speech.RecognizeResponse], + Union[ + cloud_speech.RecognizeResponse, Awaitable[cloud_speech.RecognizeResponse] ], ]: raise NotImplementedError() @@ -161,20 +222,20 @@ def recognize( @property def long_running_recognize( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech.LongRunningRecognizeRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def streaming_recognize( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_speech.StreamingRecognizeRequest], - typing.Union[ + Union[ cloud_speech.StreamingRecognizeResponse, - typing.Awaitable[cloud_speech.StreamingRecognizeResponse], + Awaitable[cloud_speech.StreamingRecognizeResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py index fa3acc83..422a571e 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import SpeechTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -177,7 +175,7 @@ def __init__( def create_channel( cls, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -208,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -268,7 +268,7 @@ def recognize( @property def long_running_recognize( self, - ) -> Callable[[cloud_speech.LongRunningRecognizeRequest], operations.Operation]: + ) -> Callable[[cloud_speech.LongRunningRecognizeRequest], operations_pb2.Operation]: r"""Return a callable for the long running recognize method over gRPC. Performs asynchronous speech recognition: receive results via @@ -292,7 +292,7 @@ def long_running_recognize( self._stubs["long_running_recognize"] = self.grpc_channel.unary_unary( "/google.cloud.speech.v1p1beta1.Speech/LongRunningRecognize", request_serializer=cloud_speech.LongRunningRecognizeRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["long_running_recognize"] diff --git a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py index 7a63ac9f..1bfc2094 100644 --- a/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py +++ b/google/cloud/speech_v1p1beta1/services/speech/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.speech_v1p1beta1.types import cloud_speech -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import SpeechTransport, DEFAULT_CLIENT_INFO from .grpc import SpeechGrpcTransport @@ -55,7 +52,7 @@ class SpeechGrpcAsyncIOTransport(SpeechTransport): def create_channel( cls, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "speech.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -277,7 +276,7 @@ def recognize( def long_running_recognize( self, ) -> Callable[ - [cloud_speech.LongRunningRecognizeRequest], Awaitable[operations.Operation] + [cloud_speech.LongRunningRecognizeRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the long running recognize method over gRPC. @@ -302,7 +301,7 @@ def long_running_recognize( self._stubs["long_running_recognize"] = self.grpc_channel.unary_unary( "/google.cloud.speech.v1p1beta1.Speech/LongRunningRecognize", request_serializer=cloud_speech.LongRunningRecognizeRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["long_running_recognize"] diff --git a/google/cloud/speech_v1p1beta1/types/__init__.py b/google/cloud/speech_v1p1beta1/types/__init__.py index 06d92d08..1274808d 100644 --- a/google/cloud/speech_v1p1beta1/types/__init__.py +++ b/google/cloud/speech_v1p1beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .cloud_speech import ( LongRunningRecognizeMetadata, LongRunningRecognizeRequest, diff --git a/google/cloud/speech_v1p1beta1/types/cloud_speech.py b/google/cloud/speech_v1p1beta1/types/cloud_speech.py index 02b49c25..1bf91ab6 100644 --- a/google/cloud/speech_v1p1beta1/types/cloud_speech.py +++ b/google/cloud/speech_v1p1beta1/types/cloud_speech.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.speech_v1p1beta1.types import resource -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.protobuf import wrappers_pb2 as wrappers # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -64,7 +61,6 @@ class RecognizeRequest(proto.Message): """ config = proto.Field(proto.MESSAGE, number=1, message="RecognitionConfig",) - audio = proto.Field(proto.MESSAGE, number=2, message="RecognitionAudio",) @@ -85,9 +81,7 @@ class LongRunningRecognizeRequest(proto.Message): """ config = proto.Field(proto.MESSAGE, number=1, message="RecognitionConfig",) - audio = proto.Field(proto.MESSAGE, number=2, message="RecognitionAudio",) - output_config = proto.Field( proto.MESSAGE, number=4, message="TranscriptOutputConfig", ) @@ -105,7 +99,7 @@ class TranscriptOutputConfig(proto.Message): already exist. """ - gcs_uri = proto.Field(proto.STRING, number=1, oneof="output_type") + gcs_uri = proto.Field(proto.STRING, number=1, oneof="output_type",) class StreamingRecognizeRequest(proto.Message): @@ -141,8 +135,7 @@ class StreamingRecognizeRequest(proto.Message): oneof="streaming_request", message="StreamingRecognitionConfig", ) - - audio_content = proto.Field(proto.BYTES, number=2, oneof="streaming_request") + audio_content = proto.Field(proto.BYTES, number=2, oneof="streaming_request",) class StreamingRecognitionConfig(proto.Message): @@ -188,10 +181,8 @@ class StreamingRecognitionConfig(proto.Message): """ config = proto.Field(proto.MESSAGE, number=1, message="RecognitionConfig",) - - single_utterance = proto.Field(proto.BOOL, number=2) - - interim_results = proto.Field(proto.BOOL, number=3) + single_utterance = proto.Field(proto.BOOL, number=2,) + interim_results = proto.Field(proto.BOOL, number=3,) class RecognitionConfig(proto.Message): @@ -363,7 +354,7 @@ class RecognitionConfig(proto.Message): video - Best for audio that originated from from video or includes multiple + Best for audio that originated from video or includes multiple speakers. Ideally the audio is recorded at a 16khz or greater sampling rate. This is a premium model that costs more than the standard rate. @@ -423,63 +414,43 @@ class AudioEncoding(proto.Enum): OGG_OPUS = 6 SPEEX_WITH_HEADER_BYTE = 7 MP3 = 8 + WEBM_OPUS = 9 encoding = proto.Field(proto.ENUM, number=1, enum=AudioEncoding,) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - - audio_channel_count = proto.Field(proto.INT32, number=7) - - enable_separate_recognition_per_channel = proto.Field(proto.BOOL, number=12) - - language_code = proto.Field(proto.STRING, number=3) - - alternative_language_codes = proto.RepeatedField(proto.STRING, number=18) - - max_alternatives = proto.Field(proto.INT32, number=4) - - profanity_filter = proto.Field(proto.BOOL, number=5) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) + audio_channel_count = proto.Field(proto.INT32, number=7,) + enable_separate_recognition_per_channel = proto.Field(proto.BOOL, number=12,) + language_code = proto.Field(proto.STRING, number=3,) + alternative_language_codes = proto.RepeatedField(proto.STRING, number=18,) + max_alternatives = proto.Field(proto.INT32, number=4,) + profanity_filter = proto.Field(proto.BOOL, number=5,) adaptation = proto.Field( proto.MESSAGE, number=20, message=resource.SpeechAdaptation, ) - speech_contexts = proto.RepeatedField( proto.MESSAGE, number=6, message="SpeechContext", ) - - enable_word_time_offsets = proto.Field(proto.BOOL, number=8) - - enable_word_confidence = proto.Field(proto.BOOL, number=15) - - enable_automatic_punctuation = proto.Field(proto.BOOL, number=11) - + enable_word_time_offsets = proto.Field(proto.BOOL, number=8,) + enable_word_confidence = proto.Field(proto.BOOL, number=15,) + enable_automatic_punctuation = proto.Field(proto.BOOL, number=11,) enable_spoken_punctuation = proto.Field( - proto.MESSAGE, number=22, message=wrappers.BoolValue, + proto.MESSAGE, number=22, message=wrappers_pb2.BoolValue, ) - enable_spoken_emojis = proto.Field( - proto.MESSAGE, number=23, message=wrappers.BoolValue, + proto.MESSAGE, number=23, message=wrappers_pb2.BoolValue, ) - - enable_speaker_diarization = proto.Field(proto.BOOL, number=16) - - diarization_speaker_count = proto.Field(proto.INT32, number=17) - + enable_speaker_diarization = proto.Field(proto.BOOL, number=16,) + diarization_speaker_count = proto.Field(proto.INT32, number=17,) diarization_config = proto.Field( proto.MESSAGE, number=19, message="SpeakerDiarizationConfig", ) - metadata = proto.Field(proto.MESSAGE, number=9, message="RecognitionMetadata",) - - model = proto.Field(proto.STRING, number=13) - - use_enhanced = proto.Field(proto.BOOL, number=14) + model = proto.Field(proto.STRING, number=13,) + use_enhanced = proto.Field(proto.BOOL, number=14,) class SpeakerDiarizationConfig(proto.Message): r"""Config to enable speaker diarization. - Attributes: enable_speaker_diarization (bool): If 'true', enables speaker detection for each recognized @@ -501,18 +472,14 @@ class SpeakerDiarizationConfig(proto.Message): Output only. Unused. """ - enable_speaker_diarization = proto.Field(proto.BOOL, number=1) - - min_speaker_count = proto.Field(proto.INT32, number=2) - - max_speaker_count = proto.Field(proto.INT32, number=3) - - speaker_tag = proto.Field(proto.INT32, number=5) + enable_speaker_diarization = proto.Field(proto.BOOL, number=1,) + min_speaker_count = proto.Field(proto.INT32, number=2,) + max_speaker_count = proto.Field(proto.INT32, number=3,) + speaker_tag = proto.Field(proto.INT32, number=5,) class RecognitionMetadata(proto.Message): r"""Description of audio data to be recognized. - Attributes: interaction_type (google.cloud.speech_v1p1beta1.types.RecognitionMetadata.InteractionType): The use case most closely describing the @@ -593,22 +560,14 @@ class RecordingDeviceType(proto.Enum): OTHER_INDOOR_DEVICE = 6 interaction_type = proto.Field(proto.ENUM, number=1, enum=InteractionType,) - - industry_naics_code_of_audio = proto.Field(proto.UINT32, number=3) - + industry_naics_code_of_audio = proto.Field(proto.UINT32, number=3,) microphone_distance = proto.Field(proto.ENUM, number=4, enum=MicrophoneDistance,) - original_media_type = proto.Field(proto.ENUM, number=5, enum=OriginalMediaType,) - recording_device_type = proto.Field(proto.ENUM, number=6, enum=RecordingDeviceType,) - - recording_device_name = proto.Field(proto.STRING, number=7) - - original_mime_type = proto.Field(proto.STRING, number=8) - - obfuscated_id = proto.Field(proto.INT64, number=9) - - audio_topic = proto.Field(proto.STRING, number=10) + recording_device_name = proto.Field(proto.STRING, number=7,) + original_mime_type = proto.Field(proto.STRING, number=8,) + obfuscated_id = proto.Field(proto.INT64, number=9,) + audio_topic = proto.Field(proto.STRING, number=10,) class SpeechContext(proto.Message): @@ -645,9 +604,8 @@ class SpeechContext(proto.Message): optimal value for your use case. """ - phrases = proto.RepeatedField(proto.STRING, number=1) - - boost = proto.Field(proto.FLOAT, number=4) + phrases = proto.RepeatedField(proto.STRING, number=1,) + boost = proto.Field(proto.FLOAT, number=4,) class RecognitionAudio(proto.Message): @@ -676,9 +634,8 @@ class RecognitionAudio(proto.Message): URIs `__. """ - content = proto.Field(proto.BYTES, number=1, oneof="audio_source") - - uri = proto.Field(proto.STRING, number=2, oneof="audio_source") + content = proto.Field(proto.BYTES, number=1, oneof="audio_source",) + uri = proto.Field(proto.STRING, number=2, oneof="audio_source",) class RecognizeResponse(proto.Message): @@ -720,12 +677,10 @@ class LongRunningRecognizeResponse(proto.Message): results = proto.RepeatedField( proto.MESSAGE, number=2, message="SpeechRecognitionResult", ) - output_config = proto.Field( proto.MESSAGE, number=6, message="TranscriptOutputConfig", ) - - output_error = proto.Field(proto.MESSAGE, number=7, message=status.Status,) + output_error = proto.Field(proto.MESSAGE, number=7, message=status_pb2.Status,) class LongRunningRecognizeMetadata(proto.Message): @@ -753,16 +708,12 @@ class LongRunningRecognizeMetadata(proto.Message): request. """ - progress_percent = proto.Field(proto.INT32, number=1) - - start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - + progress_percent = proto.Field(proto.INT32, number=1,) + start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) last_update_time = proto.Field( - proto.MESSAGE, number=3, message=timestamp.Timestamp, + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, ) - - uri = proto.Field(proto.STRING, number=4) - + uri = proto.Field(proto.STRING, number=4,) output_config = proto.Field( proto.MESSAGE, number=5, message="TranscriptOutputConfig", ) @@ -841,12 +792,10 @@ class SpeechEventType(proto.Enum): SPEECH_EVENT_UNSPECIFIED = 0 END_OF_SINGLE_UTTERANCE = 1 - error = proto.Field(proto.MESSAGE, number=1, message=status.Status,) - + error = proto.Field(proto.MESSAGE, number=1, message=status_pb2.Status,) results = proto.RepeatedField( proto.MESSAGE, number=2, message="StreamingRecognitionResult", ) - speech_event_type = proto.Field(proto.ENUM, number=4, enum=SpeechEventType,) @@ -894,16 +843,13 @@ class StreamingRecognitionResult(proto.Message): alternatives = proto.RepeatedField( proto.MESSAGE, number=1, message="SpeechRecognitionAlternative", ) - - is_final = proto.Field(proto.BOOL, number=2) - - stability = proto.Field(proto.FLOAT, number=3) - - result_end_time = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) - - channel_tag = proto.Field(proto.INT32, number=5) - - language_code = proto.Field(proto.STRING, number=6) + is_final = proto.Field(proto.BOOL, number=2,) + stability = proto.Field(proto.FLOAT, number=3,) + result_end_time = proto.Field( + proto.MESSAGE, number=4, message=duration_pb2.Duration, + ) + channel_tag = proto.Field(proto.INT32, number=5,) + language_code = proto.Field(proto.STRING, number=6,) class SpeechRecognitionResult(proto.Message): @@ -933,15 +879,12 @@ class SpeechRecognitionResult(proto.Message): alternatives = proto.RepeatedField( proto.MESSAGE, number=1, message="SpeechRecognitionAlternative", ) - - channel_tag = proto.Field(proto.INT32, number=2) - - language_code = proto.Field(proto.STRING, number=5) + channel_tag = proto.Field(proto.INT32, number=2,) + language_code = proto.Field(proto.STRING, number=5,) class SpeechRecognitionAlternative(proto.Message): r"""Alternative hypotheses (a.k.a. n-best list). - Attributes: transcript (str): Transcript text representing the words that @@ -961,16 +904,13 @@ class SpeechRecognitionAlternative(proto.Message): will see all the words from the beginning of the audio. """ - transcript = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) - + transcript = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) words = proto.RepeatedField(proto.MESSAGE, number=3, message="WordInfo",) class WordInfo(proto.Message): r"""Word-specific information for recognized words. - Attributes: start_time (google.protobuf.duration_pb2.Duration): Time offset relative to the beginning of the audio, and @@ -1005,15 +945,11 @@ class WordInfo(proto.Message): top alternative. """ - start_time = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) - - end_time = proto.Field(proto.MESSAGE, number=2, message=duration.Duration,) - - word = proto.Field(proto.STRING, number=3) - - confidence = proto.Field(proto.FLOAT, number=4) - - speaker_tag = proto.Field(proto.INT32, number=5) + start_time = proto.Field(proto.MESSAGE, number=1, message=duration_pb2.Duration,) + end_time = proto.Field(proto.MESSAGE, number=2, message=duration_pb2.Duration,) + word = proto.Field(proto.STRING, number=3,) + confidence = proto.Field(proto.FLOAT, number=4,) + speaker_tag = proto.Field(proto.INT32, number=5,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py b/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py index e1d92dad..d9bd5ea8 100644 --- a/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py +++ b/google/cloud/speech_v1p1beta1/types/cloud_speech_adaptation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.speech_v1p1beta1.types import resource -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -43,7 +40,6 @@ class CreatePhraseSetRequest(proto.Message): r"""Message sent by the client for the ``CreatePhraseSet`` method. - Attributes: parent (str): Required. The parent resource where this phrase set will be @@ -59,16 +55,13 @@ class CreatePhraseSetRequest(proto.Message): Required. The phrase set to create. """ - parent = proto.Field(proto.STRING, number=1) - - phrase_set_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + phrase_set_id = proto.Field(proto.STRING, number=2,) phrase_set = proto.Field(proto.MESSAGE, number=3, message=resource.PhraseSet,) class UpdatePhraseSetRequest(proto.Message): r"""Message sent by the client for the ``UpdatePhraseSet`` method. - Attributes: phrase_set (google.cloud.speech_v1p1beta1.types.PhraseSet): Required. The phrase set to update. @@ -81,25 +74,24 @@ class UpdatePhraseSetRequest(proto.Message): """ phrase_set = proto.Field(proto.MESSAGE, number=1, message=resource.PhraseSet,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class GetPhraseSetRequest(proto.Message): r"""Message sent by the client for the ``GetPhraseSet`` method. - Attributes: name (str): Required. The name of the phrase set to retrieve. Format: {api_version}/projects/{project}/locations/{location}/phraseSets/{phrase_set} """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListPhraseSetRequest(proto.Message): r"""Message sent by the client for the ``ListPhraseSet`` method. - Attributes: parent (str): Required. The parent, which owns this @@ -120,16 +112,13 @@ class ListPhraseSetRequest(proto.Message): token. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListPhraseSetResponse(proto.Message): r"""Message returned to the client by the ``ListPhraseSet`` method. - Attributes: phrase_sets (Sequence[google.cloud.speech_v1p1beta1.types.PhraseSet]): The phrase set. @@ -146,25 +135,22 @@ def raw_page(self): phrase_sets = proto.RepeatedField( proto.MESSAGE, number=1, message=resource.PhraseSet, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class DeletePhraseSetRequest(proto.Message): r"""Message sent by the client for the ``DeletePhraseSet`` method. - Attributes: name (str): Required. The name of the phrase set to delete. Format: {api_version}/projects/{project}/locations/{location}/phraseSets/{phrase_set} """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateCustomClassRequest(proto.Message): r"""Message sent by the client for the ``CreateCustomClass`` method. - Attributes: parent (str): Required. The parent resource where this custom class will @@ -180,16 +166,13 @@ class CreateCustomClassRequest(proto.Message): Required. The custom class to create. """ - parent = proto.Field(proto.STRING, number=1) - - custom_class_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + custom_class_id = proto.Field(proto.STRING, number=2,) custom_class = proto.Field(proto.MESSAGE, number=3, message=resource.CustomClass,) class UpdateCustomClassRequest(proto.Message): r"""Message sent by the client for the ``UpdateCustomClass`` method. - Attributes: custom_class (google.cloud.speech_v1p1beta1.types.CustomClass): Required. The custom class to update. @@ -202,25 +185,24 @@ class UpdateCustomClassRequest(proto.Message): """ custom_class = proto.Field(proto.MESSAGE, number=1, message=resource.CustomClass,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class GetCustomClassRequest(proto.Message): r"""Message sent by the client for the ``GetCustomClass`` method. - Attributes: name (str): Required. The name of the custom class to retrieve. Format: {api_version}/projects/{project}/locations/{location}/customClasses/{custom_class} """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListCustomClassesRequest(proto.Message): r"""Message sent by the client for the ``ListCustomClasses`` method. - Attributes: parent (str): Required. The parent, which owns this collection of custom @@ -241,16 +223,13 @@ class ListCustomClassesRequest(proto.Message): page token. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListCustomClassesResponse(proto.Message): r"""Message returned to the client by the ``ListCustomClasses`` method. - Attributes: custom_classes (Sequence[google.cloud.speech_v1p1beta1.types.CustomClass]): The custom classes. @@ -267,20 +246,18 @@ def raw_page(self): custom_classes = proto.RepeatedField( proto.MESSAGE, number=1, message=resource.CustomClass, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class DeleteCustomClassRequest(proto.Message): r"""Message sent by the client for the ``DeleteCustomClass`` method. - Attributes: name (str): Required. The name of the custom class to delete. Format: {api_version}/projects/{project}/locations/{location}/customClasses/{custom_class} """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/speech_v1p1beta1/types/resource.py b/google/cloud/speech_v1p1beta1/types/resource.py index a9d06af7..1e709d8e 100644 --- a/google/cloud/speech_v1p1beta1/types/resource.py +++ b/google/cloud/speech_v1p1beta1/types/resource.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -42,18 +40,15 @@ class CustomClass(proto.Message): class ClassItem(proto.Message): r"""An item of the class. - Attributes: value (str): The class item's value. """ - value = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - custom_class_id = proto.Field(proto.STRING, number=2) + value = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) + custom_class_id = proto.Field(proto.STRING, number=2,) items = proto.RepeatedField(proto.MESSAGE, number=3, message=ClassItem,) @@ -122,20 +117,16 @@ class Phrase(proto.Message): skip PhraseSets with a boost value of 0. """ - value = proto.Field(proto.STRING, number=1) - - boost = proto.Field(proto.FLOAT, number=2) - - name = proto.Field(proto.STRING, number=1) + value = proto.Field(proto.STRING, number=1,) + boost = proto.Field(proto.FLOAT, number=2,) + name = proto.Field(proto.STRING, number=1,) phrases = proto.RepeatedField(proto.MESSAGE, number=2, message=Phrase,) - - boost = proto.Field(proto.FLOAT, number=4) + boost = proto.Field(proto.FLOAT, number=4,) class SpeechAdaptation(proto.Message): r"""Speech adaptation configuration. - Attributes: phrase_sets (Sequence[google.cloud.speech_v1p1beta1.types.PhraseSet]): A collection of phrase sets. To specify the hints inline, @@ -153,9 +144,7 @@ class SpeechAdaptation(proto.Message): """ phrase_sets = proto.RepeatedField(proto.MESSAGE, number=1, message="PhraseSet",) - - phrase_set_references = proto.RepeatedField(proto.STRING, number=2) - + phrase_set_references = proto.RepeatedField(proto.STRING, number=2,) custom_classes = proto.RepeatedField( proto.MESSAGE, number=3, message="CustomClass", ) diff --git a/scripts/fixup_speech_v1_keywords.py b/scripts/fixup_speech_v1_keywords.py index bcc5ab74..385dac85 100644 --- a/scripts/fixup_speech_v1_keywords.py +++ b/scripts/fixup_speech_v1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,10 +39,9 @@ def partition( class speechCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'long_running_recognize': ('config', 'audio', ), - 'recognize': ('config', 'audio', ), - 'streaming_recognize': ('streaming_config', 'audio_content', ), - + 'long_running_recognize': ('config', 'audio', ), + 'recognize': ('config', 'audio', ), + 'streaming_recognize': ('streaming_config', 'audio_content', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -75,7 +72,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_speech_v1p1beta1_keywords.py b/scripts/fixup_speech_v1p1beta1_keywords.py index 8c79edec..4701246e 100644 --- a/scripts/fixup_speech_v1p1beta1_keywords.py +++ b/scripts/fixup_speech_v1p1beta1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,20 +39,19 @@ def partition( class speechCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_custom_class': ('parent', 'custom_class', 'custom_class_id', ), - 'create_phrase_set': ('parent', 'phrase_set', 'phrase_set_id', ), - 'delete_custom_class': ('name', ), - 'delete_phrase_set': ('name', ), - 'get_custom_class': ('name', ), - 'get_phrase_set': ('name', ), - 'list_custom_classes': ('parent', 'page_size', 'page_token', ), - 'list_phrase_set': ('parent', 'page_size', 'page_token', ), - 'long_running_recognize': ('config', 'audio', 'output_config', ), - 'recognize': ('config', 'audio', ), - 'streaming_recognize': ('streaming_config', 'audio_content', ), - 'update_custom_class': ('custom_class', 'update_mask', ), - 'update_phrase_set': ('phrase_set', 'update_mask', ), - + 'create_custom_class': ('parent', 'custom_class', 'custom_class_id', ), + 'create_phrase_set': ('parent', 'phrase_set', 'phrase_set_id', ), + 'delete_custom_class': ('name', ), + 'delete_phrase_set': ('name', ), + 'get_custom_class': ('name', ), + 'get_phrase_set': ('name', ), + 'list_custom_classes': ('parent', 'page_size', 'page_token', ), + 'list_phrase_set': ('parent', 'page_size', 'page_token', ), + 'long_running_recognize': ('config', 'audio', 'output_config', ), + 'recognize': ('config', 'audio', ), + 'streaming_recognize': ('streaming_config', 'audio_content', ), + 'update_custom_class': ('custom_class', 'update_mask', ), + 'update_phrase_set': ('phrase_set', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -85,7 +82,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/setup.py b/setup.py index 609c6f89..65a9ee14 100644 --- a/setup.py +++ b/setup.py @@ -32,6 +32,7 @@ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "libcst >= 0.2.5", "proto-plus >= 1.4.0", + "packaging >= 14.3", ] extras = {} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index c9338875..7f0da877 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -7,4 +7,5 @@ # Then this file should have foo==1.14.0 google-api-core==1.22.2 libcst==0.2.5 -proto-plus==1.4.0 \ No newline at end of file +proto-plus==1.4.0 +google-auth==1.24.0 # TODO: Remove when google-auth >= 1.25.0 is required transitively through google-api-core diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/gapic/speech_v1/__init__.py b/tests/unit/gapic/speech_v1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/speech_v1/__init__.py +++ b/tests/unit/gapic/speech_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/speech_v1/test_speech.py b/tests/unit/gapic/speech_v1/test_speech.py index 2e28d565..a7748d3a 100644 --- a/tests/unit/gapic/speech_v1/test_speech.py +++ b/tests/unit/gapic/speech_v1/test_speech.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,24 +23,50 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.speech_v1.services.speech import SpeechAsyncClient from google.cloud.speech_v1.services.speech import SpeechClient from google.cloud.speech_v1.services.speech import transports +from google.cloud.speech_v1.services.speech.transports.base import _API_CORE_VERSION +from google.cloud.speech_v1.services.speech.transports.base import _GOOGLE_AUTH_VERSION from google.cloud.speech_v1.types import cloud_speech from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.rpc import status_pb2 as status # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -84,7 +109,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SpeechClient, SpeechAsyncClient,]) def test_speech_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +124,7 @@ def test_speech_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SpeechClient, SpeechAsyncClient,]) def test_speech_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -142,7 +167,7 @@ def test_speech_client_get_transport_class(): def test_speech_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(SpeechClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -414,7 +439,7 @@ def test_speech_client_client_options_from_dict(): def test_recognize(transport: str = "grpc", request_type=cloud_speech.RecognizeRequest): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -425,17 +450,14 @@ def test_recognize(transport: str = "grpc", request_type=cloud_speech.RecognizeR with mock.patch.object(type(client.transport.recognize), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloud_speech.RecognizeResponse() - response = client.recognize(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.RecognizeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, cloud_speech.RecognizeResponse) @@ -447,7 +469,7 @@ def test_recognize_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -455,7 +477,6 @@ def test_recognize_empty_call(): client.recognize() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.RecognizeRequest() @@ -464,7 +485,7 @@ async def test_recognize_async( transport: str = "grpc_asyncio", request_type=cloud_speech.RecognizeRequest ): client = SpeechAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -477,13 +498,11 @@ async def test_recognize_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_speech.RecognizeResponse() ) - response = await client.recognize(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.RecognizeRequest() # Establish that the response is the type that we expect. @@ -496,13 +515,12 @@ async def test_recognize_async_from_dict(): def test_recognize_flattened(): - client = SpeechClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.recognize), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloud_speech.RecognizeResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.recognize( @@ -516,16 +534,14 @@ def test_recognize_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].config == cloud_speech.RecognitionConfig( encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 ) - assert args[0].audio == cloud_speech.RecognitionAudio(content=b"content_blob") def test_recognize_flattened_error(): - client = SpeechClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -541,7 +557,7 @@ def test_recognize_flattened_error(): @pytest.mark.asyncio async def test_recognize_flattened_async(): - client = SpeechAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.recognize), "__call__") as call: @@ -564,17 +580,15 @@ async def test_recognize_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].config == cloud_speech.RecognitionConfig( encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 ) - assert args[0].audio == cloud_speech.RecognitionAudio(content=b"content_blob") @pytest.mark.asyncio async def test_recognize_flattened_error_async(): - client = SpeechAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -592,7 +606,7 @@ def test_long_running_recognize( transport: str = "grpc", request_type=cloud_speech.LongRunningRecognizeRequest ): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -605,13 +619,11 @@ def test_long_running_recognize( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.long_running_recognize(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.LongRunningRecognizeRequest() # Establish that the response is the type that we expect. @@ -626,7 +638,7 @@ def test_long_running_recognize_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -636,7 +648,6 @@ def test_long_running_recognize_empty_call(): client.long_running_recognize() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.LongRunningRecognizeRequest() @@ -646,7 +657,7 @@ async def test_long_running_recognize_async( request_type=cloud_speech.LongRunningRecognizeRequest, ): client = SpeechAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -661,13 +672,11 @@ async def test_long_running_recognize_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.long_running_recognize(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.LongRunningRecognizeRequest() # Establish that the response is the type that we expect. @@ -680,7 +689,7 @@ async def test_long_running_recognize_async_from_dict(): def test_long_running_recognize_flattened(): - client = SpeechClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -688,7 +697,6 @@ def test_long_running_recognize_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.long_running_recognize( @@ -702,16 +710,14 @@ def test_long_running_recognize_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].config == cloud_speech.RecognitionConfig( encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 ) - assert args[0].audio == cloud_speech.RecognitionAudio(content=b"content_blob") def test_long_running_recognize_flattened_error(): - client = SpeechClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -727,7 +733,7 @@ def test_long_running_recognize_flattened_error(): @pytest.mark.asyncio async def test_long_running_recognize_flattened_async(): - client = SpeechAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -752,17 +758,15 @@ async def test_long_running_recognize_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].config == cloud_speech.RecognitionConfig( encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 ) - assert args[0].audio == cloud_speech.RecognitionAudio(content=b"content_blob") @pytest.mark.asyncio async def test_long_running_recognize_flattened_error_async(): - client = SpeechAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -780,13 +784,12 @@ def test_streaming_recognize( transport: str = "grpc", request_type=cloud_speech.StreamingRecognizeRequest ): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -795,13 +798,11 @@ def test_streaming_recognize( ) as call: # Designate an appropriate return value for the call. call.return_value = iter([cloud_speech.StreamingRecognizeResponse()]) - response = client.streaming_recognize(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -818,13 +819,12 @@ async def test_streaming_recognize_async( transport: str = "grpc_asyncio", request_type=cloud_speech.StreamingRecognizeRequest ): client = SpeechAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -836,13 +836,11 @@ async def test_streaming_recognize_async( call.return_value.read = mock.AsyncMock( side_effect=[cloud_speech.StreamingRecognizeResponse()] ) - response = await client.streaming_recognize(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -858,16 +856,16 @@ async def test_streaming_recognize_async_from_dict(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SpeechGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SpeechGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechClient( @@ -877,7 +875,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SpeechGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechClient( @@ -888,7 +886,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SpeechGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SpeechClient(transport=transport) assert client.transport is transport @@ -897,13 +895,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SpeechGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SpeechGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -915,23 +913,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = SpeechClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.SpeechGrpcTransport,) def test_speech_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SpeechTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -943,7 +941,7 @@ def test_speech_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SpeechTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -963,15 +961,37 @@ def test_speech_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_speech_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.speech_v1.services.speech.transports.SpeechTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SpeechTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_speech_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.speech_v1.services.speech.transports.SpeechTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SpeechTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -984,19 +1004,33 @@ def test_speech_base_transport_with_credentials_file(): def test_speech_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.speech_v1.services.speech.transports.SpeechTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SpeechTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_speech_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SpeechClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_speech_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) SpeechClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -1004,26 +1038,152 @@ def test_speech_auth_adc(): ) -def test_speech_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.SpeechGrpcTransport, transports.SpeechGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_speech_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SpeechGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.SpeechGrpcTransport, transports.SpeechGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_speech_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SpeechGrpcTransport, grpc_helpers), + (transports.SpeechGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_speech_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "speech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="speech.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SpeechGrpcTransport, grpc_helpers), + (transports.SpeechGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_speech_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "speech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SpeechGrpcTransport, grpc_helpers), + (transports.SpeechGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_speech_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "speech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.SpeechGrpcTransport, transports.SpeechGrpcAsyncIOTransport], ) def test_speech_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1062,7 +1222,7 @@ def test_speech_grpc_transport_client_cert_source_for_mtls(transport_class): def test_speech_host_no_port(): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="speech.googleapis.com" ), @@ -1072,7 +1232,7 @@ def test_speech_host_no_port(): def test_speech_host_with_port(): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="speech.googleapis.com:8000" ), @@ -1123,9 +1283,9 @@ def test_speech_transport_channel_mtls_with_client_cert_source(transport_class): mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1198,7 +1358,7 @@ def test_speech_transport_channel_mtls_with_adc(transport_class): def test_speech_grpc_lro_client(): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1211,7 +1371,7 @@ def test_speech_grpc_lro_client(): def test_speech_grpc_lro_async_client(): client = SpeechAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1224,7 +1384,6 @@ def test_speech_grpc_lro_async_client(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1245,7 +1404,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = SpeechClient.common_folder_path(folder) assert expected == actual @@ -1264,7 +1422,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = SpeechClient.common_organization_path(organization) assert expected == actual @@ -1283,7 +1440,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = SpeechClient.common_project_path(project) assert expected == actual @@ -1303,7 +1459,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1330,7 +1485,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SpeechTransport, "_prep_wrapped_messages" ) as prep: client = SpeechClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1339,6 +1494,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SpeechClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/speech_v1p1beta1/__init__.py b/tests/unit/gapic/speech_v1p1beta1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/speech_v1p1beta1/__init__.py +++ b/tests/unit/gapic/speech_v1p1beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/speech_v1p1beta1/test_adaptation.py b/tests/unit/gapic/speech_v1p1beta1/test_adaptation.py index 75f5f723..60ca9918 100644 --- a/tests/unit/gapic/speech_v1p1beta1/test_adaptation.py +++ b/tests/unit/gapic/speech_v1p1beta1/test_adaptation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,22 +23,52 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.speech_v1p1beta1.services.adaptation import AdaptationAsyncClient from google.cloud.speech_v1p1beta1.services.adaptation import AdaptationClient from google.cloud.speech_v1p1beta1.services.adaptation import pagers from google.cloud.speech_v1p1beta1.services.adaptation import transports +from google.cloud.speech_v1p1beta1.services.adaptation.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.speech_v1p1beta1.services.adaptation.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.speech_v1p1beta1.types import cloud_speech_adaptation from google.cloud.speech_v1p1beta1.types import resource from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -85,7 +114,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AdaptationClient, AdaptationAsyncClient,]) def test_adaptation_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -100,7 +129,7 @@ def test_adaptation_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AdaptationClient, AdaptationAsyncClient,]) def test_adaptation_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -151,7 +180,7 @@ def test_adaptation_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(AdaptationClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -435,7 +464,7 @@ def test_create_phrase_set( transport: str = "grpc", request_type=cloud_speech_adaptation.CreatePhraseSetRequest ): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -448,21 +477,16 @@ def test_create_phrase_set( ) as call: # Designate an appropriate return value for the call. call.return_value = resource.PhraseSet(name="name_value", boost=0.551,) - response = client.create_phrase_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.CreatePhraseSetRequest() # Establish that the response is the type that we expect. - assert isinstance(response, resource.PhraseSet) - assert response.name == "name_value" - assert math.isclose(response.boost, 0.551, rel_tol=1e-6) @@ -474,7 +498,7 @@ def test_create_phrase_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -484,7 +508,6 @@ def test_create_phrase_set_empty_call(): client.create_phrase_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.CreatePhraseSetRequest() @@ -494,7 +517,7 @@ async def test_create_phrase_set_async( request_type=cloud_speech_adaptation.CreatePhraseSetRequest, ): client = AdaptationAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -509,20 +532,16 @@ async def test_create_phrase_set_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resource.PhraseSet(name="name_value", boost=0.551,) ) - response = await client.create_phrase_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.CreatePhraseSetRequest() # Establish that the response is the type that we expect. assert isinstance(response, resource.PhraseSet) - assert response.name == "name_value" - assert math.isclose(response.boost, 0.551, rel_tol=1e-6) @@ -532,11 +551,12 @@ async def test_create_phrase_set_async_from_dict(): def test_create_phrase_set_field_headers(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.CreatePhraseSetRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -544,7 +564,6 @@ def test_create_phrase_set_field_headers(): type(client.transport.create_phrase_set), "__call__" ) as call: call.return_value = resource.PhraseSet() - client.create_phrase_set(request) # Establish that the underlying gRPC stub method was called. @@ -559,11 +578,12 @@ def test_create_phrase_set_field_headers(): @pytest.mark.asyncio async def test_create_phrase_set_field_headers_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.CreatePhraseSetRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -571,7 +591,6 @@ async def test_create_phrase_set_field_headers_async(): type(client.transport.create_phrase_set), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.PhraseSet()) - await client.create_phrase_set(request) # Establish that the underlying gRPC stub method was called. @@ -585,7 +604,7 @@ async def test_create_phrase_set_field_headers_async(): def test_create_phrase_set_flattened(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -593,7 +612,6 @@ def test_create_phrase_set_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = resource.PhraseSet() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_phrase_set( @@ -606,16 +624,13 @@ def test_create_phrase_set_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].phrase_set == resource.PhraseSet(name="name_value") - assert args[0].phrase_set_id == "phrase_set_id_value" def test_create_phrase_set_flattened_error(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -630,7 +645,7 @@ def test_create_phrase_set_flattened_error(): @pytest.mark.asyncio async def test_create_phrase_set_flattened_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -652,17 +667,14 @@ async def test_create_phrase_set_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].phrase_set == resource.PhraseSet(name="name_value") - assert args[0].phrase_set_id == "phrase_set_id_value" @pytest.mark.asyncio async def test_create_phrase_set_flattened_error_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -679,7 +691,7 @@ def test_get_phrase_set( transport: str = "grpc", request_type=cloud_speech_adaptation.GetPhraseSetRequest ): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -690,21 +702,16 @@ def test_get_phrase_set( with mock.patch.object(type(client.transport.get_phrase_set), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resource.PhraseSet(name="name_value", boost=0.551,) - response = client.get_phrase_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.GetPhraseSetRequest() # Establish that the response is the type that we expect. - assert isinstance(response, resource.PhraseSet) - assert response.name == "name_value" - assert math.isclose(response.boost, 0.551, rel_tol=1e-6) @@ -716,7 +723,7 @@ def test_get_phrase_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -724,7 +731,6 @@ def test_get_phrase_set_empty_call(): client.get_phrase_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.GetPhraseSetRequest() @@ -734,7 +740,7 @@ async def test_get_phrase_set_async( request_type=cloud_speech_adaptation.GetPhraseSetRequest, ): client = AdaptationAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -747,20 +753,16 @@ async def test_get_phrase_set_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resource.PhraseSet(name="name_value", boost=0.551,) ) - response = await client.get_phrase_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.GetPhraseSetRequest() # Establish that the response is the type that we expect. assert isinstance(response, resource.PhraseSet) - assert response.name == "name_value" - assert math.isclose(response.boost, 0.551, rel_tol=1e-6) @@ -770,17 +772,17 @@ async def test_get_phrase_set_async_from_dict(): def test_get_phrase_set_field_headers(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.GetPhraseSetRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_phrase_set), "__call__") as call: call.return_value = resource.PhraseSet() - client.get_phrase_set(request) # Establish that the underlying gRPC stub method was called. @@ -795,17 +797,17 @@ def test_get_phrase_set_field_headers(): @pytest.mark.asyncio async def test_get_phrase_set_field_headers_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.GetPhraseSetRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_phrase_set), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.PhraseSet()) - await client.get_phrase_set(request) # Establish that the underlying gRPC stub method was called. @@ -819,13 +821,12 @@ async def test_get_phrase_set_field_headers_async(): def test_get_phrase_set_flattened(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_phrase_set), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resource.PhraseSet() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_phrase_set(name="name_value",) @@ -834,12 +835,11 @@ def test_get_phrase_set_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_phrase_set_flattened_error(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -851,7 +851,7 @@ def test_get_phrase_set_flattened_error(): @pytest.mark.asyncio async def test_get_phrase_set_flattened_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_phrase_set), "__call__") as call: @@ -867,13 +867,12 @@ async def test_get_phrase_set_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_phrase_set_flattened_error_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -887,7 +886,7 @@ def test_list_phrase_set( transport: str = "grpc", request_type=cloud_speech_adaptation.ListPhraseSetRequest ): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -900,19 +899,15 @@ def test_list_phrase_set( call.return_value = cloud_speech_adaptation.ListPhraseSetResponse( next_page_token="next_page_token_value", ) - response = client.list_phrase_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.ListPhraseSetRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPhraseSetPager) - assert response.next_page_token == "next_page_token_value" @@ -924,7 +919,7 @@ def test_list_phrase_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -932,7 +927,6 @@ def test_list_phrase_set_empty_call(): client.list_phrase_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.ListPhraseSetRequest() @@ -942,7 +936,7 @@ async def test_list_phrase_set_async( request_type=cloud_speech_adaptation.ListPhraseSetRequest, ): client = AdaptationAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -957,18 +951,15 @@ async def test_list_phrase_set_async( next_page_token="next_page_token_value", ) ) - response = await client.list_phrase_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.ListPhraseSetRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPhraseSetAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -978,17 +969,17 @@ async def test_list_phrase_set_async_from_dict(): def test_list_phrase_set_field_headers(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.ListPhraseSetRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_phrase_set), "__call__") as call: call.return_value = cloud_speech_adaptation.ListPhraseSetResponse() - client.list_phrase_set(request) # Establish that the underlying gRPC stub method was called. @@ -1003,11 +994,12 @@ def test_list_phrase_set_field_headers(): @pytest.mark.asyncio async def test_list_phrase_set_field_headers_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.ListPhraseSetRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1015,7 +1007,6 @@ async def test_list_phrase_set_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_speech_adaptation.ListPhraseSetResponse() ) - await client.list_phrase_set(request) # Establish that the underlying gRPC stub method was called. @@ -1029,13 +1020,12 @@ async def test_list_phrase_set_field_headers_async(): def test_list_phrase_set_flattened(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_phrase_set), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloud_speech_adaptation.ListPhraseSetResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_phrase_set(parent="parent_value",) @@ -1044,12 +1034,11 @@ def test_list_phrase_set_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_phrase_set_flattened_error(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1061,7 +1050,7 @@ def test_list_phrase_set_flattened_error(): @pytest.mark.asyncio async def test_list_phrase_set_flattened_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_phrase_set), "__call__") as call: @@ -1079,13 +1068,12 @@ async def test_list_phrase_set_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_phrase_set_flattened_error_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1096,7 +1084,7 @@ async def test_list_phrase_set_flattened_error_async(): def test_list_phrase_set_pager(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials,) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_phrase_set), "__call__") as call: @@ -1136,7 +1124,7 @@ def test_list_phrase_set_pager(): def test_list_phrase_set_pages(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials,) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_phrase_set), "__call__") as call: @@ -1168,7 +1156,7 @@ def test_list_phrase_set_pages(): @pytest.mark.asyncio async def test_list_phrase_set_async_pager(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1207,7 +1195,7 @@ async def test_list_phrase_set_async_pager(): @pytest.mark.asyncio async def test_list_phrase_set_async_pages(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1245,7 +1233,7 @@ def test_update_phrase_set( transport: str = "grpc", request_type=cloud_speech_adaptation.UpdatePhraseSetRequest ): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1258,21 +1246,16 @@ def test_update_phrase_set( ) as call: # Designate an appropriate return value for the call. call.return_value = resource.PhraseSet(name="name_value", boost=0.551,) - response = client.update_phrase_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.UpdatePhraseSetRequest() # Establish that the response is the type that we expect. - assert isinstance(response, resource.PhraseSet) - assert response.name == "name_value" - assert math.isclose(response.boost, 0.551, rel_tol=1e-6) @@ -1284,7 +1267,7 @@ def test_update_phrase_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1294,7 +1277,6 @@ def test_update_phrase_set_empty_call(): client.update_phrase_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.UpdatePhraseSetRequest() @@ -1304,7 +1286,7 @@ async def test_update_phrase_set_async( request_type=cloud_speech_adaptation.UpdatePhraseSetRequest, ): client = AdaptationAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1319,20 +1301,16 @@ async def test_update_phrase_set_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resource.PhraseSet(name="name_value", boost=0.551,) ) - response = await client.update_phrase_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.UpdatePhraseSetRequest() # Establish that the response is the type that we expect. assert isinstance(response, resource.PhraseSet) - assert response.name == "name_value" - assert math.isclose(response.boost, 0.551, rel_tol=1e-6) @@ -1342,11 +1320,12 @@ async def test_update_phrase_set_async_from_dict(): def test_update_phrase_set_field_headers(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.UpdatePhraseSetRequest() + request.phrase_set.name = "phrase_set.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1354,7 +1333,6 @@ def test_update_phrase_set_field_headers(): type(client.transport.update_phrase_set), "__call__" ) as call: call.return_value = resource.PhraseSet() - client.update_phrase_set(request) # Establish that the underlying gRPC stub method was called. @@ -1371,11 +1349,12 @@ def test_update_phrase_set_field_headers(): @pytest.mark.asyncio async def test_update_phrase_set_field_headers_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.UpdatePhraseSetRequest() + request.phrase_set.name = "phrase_set.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1383,7 +1362,6 @@ async def test_update_phrase_set_field_headers_async(): type(client.transport.update_phrase_set), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resource.PhraseSet()) - await client.update_phrase_set(request) # Establish that the underlying gRPC stub method was called. @@ -1399,7 +1377,7 @@ async def test_update_phrase_set_field_headers_async(): def test_update_phrase_set_flattened(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1407,26 +1385,23 @@ def test_update_phrase_set_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = resource.PhraseSet() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_phrase_set( phrase_set=resource.PhraseSet(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].phrase_set == resource.PhraseSet(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_phrase_set_flattened_error(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1434,13 +1409,13 @@ def test_update_phrase_set_flattened_error(): client.update_phrase_set( cloud_speech_adaptation.UpdatePhraseSetRequest(), phrase_set=resource.PhraseSet(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_phrase_set_flattened_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1454,22 +1429,20 @@ async def test_update_phrase_set_flattened_async(): # using the keyword arguments to the method. response = await client.update_phrase_set( phrase_set=resource.PhraseSet(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].phrase_set == resource.PhraseSet(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_phrase_set_flattened_error_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1477,7 +1450,7 @@ async def test_update_phrase_set_flattened_error_async(): await client.update_phrase_set( cloud_speech_adaptation.UpdatePhraseSetRequest(), phrase_set=resource.PhraseSet(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1485,7 +1458,7 @@ def test_delete_phrase_set( transport: str = "grpc", request_type=cloud_speech_adaptation.DeletePhraseSetRequest ): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1498,13 +1471,11 @@ def test_delete_phrase_set( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_phrase_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.DeletePhraseSetRequest() # Establish that the response is the type that we expect. @@ -1519,7 +1490,7 @@ def test_delete_phrase_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1529,7 +1500,6 @@ def test_delete_phrase_set_empty_call(): client.delete_phrase_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.DeletePhraseSetRequest() @@ -1539,7 +1509,7 @@ async def test_delete_phrase_set_async( request_type=cloud_speech_adaptation.DeletePhraseSetRequest, ): client = AdaptationAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1552,13 +1522,11 @@ async def test_delete_phrase_set_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_phrase_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.DeletePhraseSetRequest() # Establish that the response is the type that we expect. @@ -1571,11 +1539,12 @@ async def test_delete_phrase_set_async_from_dict(): def test_delete_phrase_set_field_headers(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.DeletePhraseSetRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1583,7 +1552,6 @@ def test_delete_phrase_set_field_headers(): type(client.transport.delete_phrase_set), "__call__" ) as call: call.return_value = None - client.delete_phrase_set(request) # Establish that the underlying gRPC stub method was called. @@ -1598,11 +1566,12 @@ def test_delete_phrase_set_field_headers(): @pytest.mark.asyncio async def test_delete_phrase_set_field_headers_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.DeletePhraseSetRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1610,7 +1579,6 @@ async def test_delete_phrase_set_field_headers_async(): type(client.transport.delete_phrase_set), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_phrase_set(request) # Establish that the underlying gRPC stub method was called. @@ -1624,7 +1592,7 @@ async def test_delete_phrase_set_field_headers_async(): def test_delete_phrase_set_flattened(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1632,7 +1600,6 @@ def test_delete_phrase_set_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_phrase_set(name="name_value",) @@ -1641,12 +1608,11 @@ def test_delete_phrase_set_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_phrase_set_flattened_error(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1658,7 +1624,7 @@ def test_delete_phrase_set_flattened_error(): @pytest.mark.asyncio async def test_delete_phrase_set_flattened_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1676,13 +1642,12 @@ async def test_delete_phrase_set_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_phrase_set_flattened_error_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1697,7 +1662,7 @@ def test_create_custom_class( request_type=cloud_speech_adaptation.CreateCustomClassRequest, ): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1712,21 +1677,16 @@ def test_create_custom_class( call.return_value = resource.CustomClass( name="name_value", custom_class_id="custom_class_id_value", ) - response = client.create_custom_class(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.CreateCustomClassRequest() # Establish that the response is the type that we expect. - assert isinstance(response, resource.CustomClass) - assert response.name == "name_value" - assert response.custom_class_id == "custom_class_id_value" @@ -1738,7 +1698,7 @@ def test_create_custom_class_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1748,7 +1708,6 @@ def test_create_custom_class_empty_call(): client.create_custom_class() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.CreateCustomClassRequest() @@ -1758,7 +1717,7 @@ async def test_create_custom_class_async( request_type=cloud_speech_adaptation.CreateCustomClassRequest, ): client = AdaptationAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1775,20 +1734,16 @@ async def test_create_custom_class_async( name="name_value", custom_class_id="custom_class_id_value", ) ) - response = await client.create_custom_class(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.CreateCustomClassRequest() # Establish that the response is the type that we expect. assert isinstance(response, resource.CustomClass) - assert response.name == "name_value" - assert response.custom_class_id == "custom_class_id_value" @@ -1798,11 +1753,12 @@ async def test_create_custom_class_async_from_dict(): def test_create_custom_class_field_headers(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.CreateCustomClassRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1810,7 +1766,6 @@ def test_create_custom_class_field_headers(): type(client.transport.create_custom_class), "__call__" ) as call: call.return_value = resource.CustomClass() - client.create_custom_class(request) # Establish that the underlying gRPC stub method was called. @@ -1825,11 +1780,12 @@ def test_create_custom_class_field_headers(): @pytest.mark.asyncio async def test_create_custom_class_field_headers_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.CreateCustomClassRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1839,7 +1795,6 @@ async def test_create_custom_class_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resource.CustomClass() ) - await client.create_custom_class(request) # Establish that the underlying gRPC stub method was called. @@ -1853,7 +1808,7 @@ async def test_create_custom_class_field_headers_async(): def test_create_custom_class_flattened(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1861,7 +1816,6 @@ def test_create_custom_class_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = resource.CustomClass() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_custom_class( @@ -1874,16 +1828,13 @@ def test_create_custom_class_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].custom_class == resource.CustomClass(name="name_value") - assert args[0].custom_class_id == "custom_class_id_value" def test_create_custom_class_flattened_error(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1898,7 +1849,7 @@ def test_create_custom_class_flattened_error(): @pytest.mark.asyncio async def test_create_custom_class_flattened_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1922,17 +1873,14 @@ async def test_create_custom_class_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].custom_class == resource.CustomClass(name="name_value") - assert args[0].custom_class_id == "custom_class_id_value" @pytest.mark.asyncio async def test_create_custom_class_flattened_error_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1949,7 +1897,7 @@ def test_get_custom_class( transport: str = "grpc", request_type=cloud_speech_adaptation.GetCustomClassRequest ): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1962,21 +1910,16 @@ def test_get_custom_class( call.return_value = resource.CustomClass( name="name_value", custom_class_id="custom_class_id_value", ) - response = client.get_custom_class(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.GetCustomClassRequest() # Establish that the response is the type that we expect. - assert isinstance(response, resource.CustomClass) - assert response.name == "name_value" - assert response.custom_class_id == "custom_class_id_value" @@ -1988,7 +1931,7 @@ def test_get_custom_class_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1996,7 +1939,6 @@ def test_get_custom_class_empty_call(): client.get_custom_class() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.GetCustomClassRequest() @@ -2006,7 +1948,7 @@ async def test_get_custom_class_async( request_type=cloud_speech_adaptation.GetCustomClassRequest, ): client = AdaptationAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2021,20 +1963,16 @@ async def test_get_custom_class_async( name="name_value", custom_class_id="custom_class_id_value", ) ) - response = await client.get_custom_class(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.GetCustomClassRequest() # Establish that the response is the type that we expect. assert isinstance(response, resource.CustomClass) - assert response.name == "name_value" - assert response.custom_class_id == "custom_class_id_value" @@ -2044,17 +1982,17 @@ async def test_get_custom_class_async_from_dict(): def test_get_custom_class_field_headers(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.GetCustomClassRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_custom_class), "__call__") as call: call.return_value = resource.CustomClass() - client.get_custom_class(request) # Establish that the underlying gRPC stub method was called. @@ -2069,11 +2007,12 @@ def test_get_custom_class_field_headers(): @pytest.mark.asyncio async def test_get_custom_class_field_headers_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.GetCustomClassRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2081,7 +2020,6 @@ async def test_get_custom_class_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resource.CustomClass() ) - await client.get_custom_class(request) # Establish that the underlying gRPC stub method was called. @@ -2095,13 +2033,12 @@ async def test_get_custom_class_field_headers_async(): def test_get_custom_class_flattened(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_custom_class), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resource.CustomClass() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_custom_class(name="name_value",) @@ -2110,12 +2047,11 @@ def test_get_custom_class_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_custom_class_flattened_error(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2127,7 +2063,7 @@ def test_get_custom_class_flattened_error(): @pytest.mark.asyncio async def test_get_custom_class_flattened_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_custom_class), "__call__") as call: @@ -2145,13 +2081,12 @@ async def test_get_custom_class_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_custom_class_flattened_error_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2166,7 +2101,7 @@ def test_list_custom_classes( request_type=cloud_speech_adaptation.ListCustomClassesRequest, ): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2181,19 +2116,15 @@ def test_list_custom_classes( call.return_value = cloud_speech_adaptation.ListCustomClassesResponse( next_page_token="next_page_token_value", ) - response = client.list_custom_classes(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.ListCustomClassesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCustomClassesPager) - assert response.next_page_token == "next_page_token_value" @@ -2205,7 +2136,7 @@ def test_list_custom_classes_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2215,7 +2146,6 @@ def test_list_custom_classes_empty_call(): client.list_custom_classes() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.ListCustomClassesRequest() @@ -2225,7 +2155,7 @@ async def test_list_custom_classes_async( request_type=cloud_speech_adaptation.ListCustomClassesRequest, ): client = AdaptationAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2242,18 +2172,15 @@ async def test_list_custom_classes_async( next_page_token="next_page_token_value", ) ) - response = await client.list_custom_classes(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.ListCustomClassesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListCustomClassesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2263,11 +2190,12 @@ async def test_list_custom_classes_async_from_dict(): def test_list_custom_classes_field_headers(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.ListCustomClassesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2275,7 +2203,6 @@ def test_list_custom_classes_field_headers(): type(client.transport.list_custom_classes), "__call__" ) as call: call.return_value = cloud_speech_adaptation.ListCustomClassesResponse() - client.list_custom_classes(request) # Establish that the underlying gRPC stub method was called. @@ -2290,11 +2217,12 @@ def test_list_custom_classes_field_headers(): @pytest.mark.asyncio async def test_list_custom_classes_field_headers_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.ListCustomClassesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2304,7 +2232,6 @@ async def test_list_custom_classes_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_speech_adaptation.ListCustomClassesResponse() ) - await client.list_custom_classes(request) # Establish that the underlying gRPC stub method was called. @@ -2318,7 +2245,7 @@ async def test_list_custom_classes_field_headers_async(): def test_list_custom_classes_flattened(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2326,7 +2253,6 @@ def test_list_custom_classes_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = cloud_speech_adaptation.ListCustomClassesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_custom_classes(parent="parent_value",) @@ -2335,12 +2261,11 @@ def test_list_custom_classes_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_custom_classes_flattened_error(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2352,7 +2277,7 @@ def test_list_custom_classes_flattened_error(): @pytest.mark.asyncio async def test_list_custom_classes_flattened_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2372,13 +2297,12 @@ async def test_list_custom_classes_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_custom_classes_flattened_error_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2389,7 +2313,7 @@ async def test_list_custom_classes_flattened_error_async(): def test_list_custom_classes_pager(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials,) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2431,7 +2355,7 @@ def test_list_custom_classes_pager(): def test_list_custom_classes_pages(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials,) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2465,7 +2389,7 @@ def test_list_custom_classes_pages(): @pytest.mark.asyncio async def test_list_custom_classes_async_pager(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2506,7 +2430,7 @@ async def test_list_custom_classes_async_pager(): @pytest.mark.asyncio async def test_list_custom_classes_async_pages(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2547,7 +2471,7 @@ def test_update_custom_class( request_type=cloud_speech_adaptation.UpdateCustomClassRequest, ): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2562,21 +2486,16 @@ def test_update_custom_class( call.return_value = resource.CustomClass( name="name_value", custom_class_id="custom_class_id_value", ) - response = client.update_custom_class(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.UpdateCustomClassRequest() # Establish that the response is the type that we expect. - assert isinstance(response, resource.CustomClass) - assert response.name == "name_value" - assert response.custom_class_id == "custom_class_id_value" @@ -2588,7 +2507,7 @@ def test_update_custom_class_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2598,7 +2517,6 @@ def test_update_custom_class_empty_call(): client.update_custom_class() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.UpdateCustomClassRequest() @@ -2608,7 +2526,7 @@ async def test_update_custom_class_async( request_type=cloud_speech_adaptation.UpdateCustomClassRequest, ): client = AdaptationAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2625,20 +2543,16 @@ async def test_update_custom_class_async( name="name_value", custom_class_id="custom_class_id_value", ) ) - response = await client.update_custom_class(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.UpdateCustomClassRequest() # Establish that the response is the type that we expect. assert isinstance(response, resource.CustomClass) - assert response.name == "name_value" - assert response.custom_class_id == "custom_class_id_value" @@ -2648,11 +2562,12 @@ async def test_update_custom_class_async_from_dict(): def test_update_custom_class_field_headers(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.UpdateCustomClassRequest() + request.custom_class.name = "custom_class.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2660,7 +2575,6 @@ def test_update_custom_class_field_headers(): type(client.transport.update_custom_class), "__call__" ) as call: call.return_value = resource.CustomClass() - client.update_custom_class(request) # Establish that the underlying gRPC stub method was called. @@ -2678,11 +2592,12 @@ def test_update_custom_class_field_headers(): @pytest.mark.asyncio async def test_update_custom_class_field_headers_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.UpdateCustomClassRequest() + request.custom_class.name = "custom_class.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2692,7 +2607,6 @@ async def test_update_custom_class_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resource.CustomClass() ) - await client.update_custom_class(request) # Establish that the underlying gRPC stub method was called. @@ -2709,7 +2623,7 @@ async def test_update_custom_class_field_headers_async(): def test_update_custom_class_flattened(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2717,26 +2631,23 @@ def test_update_custom_class_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = resource.CustomClass() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_custom_class( custom_class=resource.CustomClass(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].custom_class == resource.CustomClass(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_custom_class_flattened_error(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2744,13 +2655,13 @@ def test_update_custom_class_flattened_error(): client.update_custom_class( cloud_speech_adaptation.UpdateCustomClassRequest(), custom_class=resource.CustomClass(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_custom_class_flattened_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2766,22 +2677,20 @@ async def test_update_custom_class_flattened_async(): # using the keyword arguments to the method. response = await client.update_custom_class( custom_class=resource.CustomClass(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].custom_class == resource.CustomClass(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_custom_class_flattened_error_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2789,7 +2698,7 @@ async def test_update_custom_class_flattened_error_async(): await client.update_custom_class( cloud_speech_adaptation.UpdateCustomClassRequest(), custom_class=resource.CustomClass(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -2798,7 +2707,7 @@ def test_delete_custom_class( request_type=cloud_speech_adaptation.DeleteCustomClassRequest, ): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2811,13 +2720,11 @@ def test_delete_custom_class( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_custom_class(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.DeleteCustomClassRequest() # Establish that the response is the type that we expect. @@ -2832,7 +2739,7 @@ def test_delete_custom_class_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2842,7 +2749,6 @@ def test_delete_custom_class_empty_call(): client.delete_custom_class() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.DeleteCustomClassRequest() @@ -2852,7 +2758,7 @@ async def test_delete_custom_class_async( request_type=cloud_speech_adaptation.DeleteCustomClassRequest, ): client = AdaptationAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2865,13 +2771,11 @@ async def test_delete_custom_class_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_custom_class(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech_adaptation.DeleteCustomClassRequest() # Establish that the response is the type that we expect. @@ -2884,11 +2788,12 @@ async def test_delete_custom_class_async_from_dict(): def test_delete_custom_class_field_headers(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.DeleteCustomClassRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2896,7 +2801,6 @@ def test_delete_custom_class_field_headers(): type(client.transport.delete_custom_class), "__call__" ) as call: call.return_value = None - client.delete_custom_class(request) # Establish that the underlying gRPC stub method was called. @@ -2911,11 +2815,12 @@ def test_delete_custom_class_field_headers(): @pytest.mark.asyncio async def test_delete_custom_class_field_headers_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = cloud_speech_adaptation.DeleteCustomClassRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2923,7 +2828,6 @@ async def test_delete_custom_class_field_headers_async(): type(client.transport.delete_custom_class), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_custom_class(request) # Establish that the underlying gRPC stub method was called. @@ -2937,7 +2841,7 @@ async def test_delete_custom_class_field_headers_async(): def test_delete_custom_class_flattened(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2945,7 +2849,6 @@ def test_delete_custom_class_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_custom_class(name="name_value",) @@ -2954,12 +2857,11 @@ def test_delete_custom_class_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_custom_class_flattened_error(): - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2971,7 +2873,7 @@ def test_delete_custom_class_flattened_error(): @pytest.mark.asyncio async def test_delete_custom_class_flattened_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2989,13 +2891,12 @@ async def test_delete_custom_class_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_custom_class_flattened_error_async(): - client = AdaptationAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3008,16 +2909,16 @@ async def test_delete_custom_class_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AdaptationGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AdaptationGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AdaptationClient( @@ -3027,7 +2928,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AdaptationGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AdaptationClient( @@ -3038,7 +2939,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AdaptationGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AdaptationClient(transport=transport) assert client.transport is transport @@ -3047,13 +2948,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AdaptationGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AdaptationGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -3065,23 +2966,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = AdaptationClient(credentials=credentials.AnonymousCredentials(),) + client = AdaptationClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.AdaptationGrpcTransport,) def test_adaptation_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AdaptationTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -3093,7 +2994,7 @@ def test_adaptation_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AdaptationTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3115,15 +3016,37 @@ def test_adaptation_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_adaptation_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.speech_v1p1beta1.services.adaptation.transports.AdaptationTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AdaptationTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_adaptation_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.speech_v1p1beta1.services.adaptation.transports.AdaptationTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AdaptationTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3136,19 +3059,33 @@ def test_adaptation_base_transport_with_credentials_file(): def test_adaptation_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.speech_v1p1beta1.services.adaptation.transports.AdaptationTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AdaptationTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_adaptation_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AdaptationClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_adaptation_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AdaptationClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -3156,26 +3093,154 @@ def test_adaptation_auth_adc(): ) -def test_adaptation_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.AdaptationGrpcTransport, transports.AdaptationGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_adaptation_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.AdaptationGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.AdaptationGrpcTransport, transports.AdaptationGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_adaptation_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AdaptationGrpcTransport, grpc_helpers), + (transports.AdaptationGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_adaptation_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "speech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="speech.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AdaptationGrpcTransport, grpc_helpers), + (transports.AdaptationGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_adaptation_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "speech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AdaptationGrpcTransport, grpc_helpers), + (transports.AdaptationGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_adaptation_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "speech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.AdaptationGrpcTransport, transports.AdaptationGrpcAsyncIOTransport], ) def test_adaptation_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -3214,7 +3279,7 @@ def test_adaptation_grpc_transport_client_cert_source_for_mtls(transport_class): def test_adaptation_host_no_port(): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="speech.googleapis.com" ), @@ -3224,7 +3289,7 @@ def test_adaptation_host_no_port(): def test_adaptation_host_with_port(): client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="speech.googleapis.com:8000" ), @@ -3275,9 +3340,9 @@ def test_adaptation_transport_channel_mtls_with_client_cert_source(transport_cla mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3352,7 +3417,6 @@ def test_custom_class_path(): project = "squid" location = "clam" custom_class = "whelk" - expected = "projects/{project}/locations/{location}/customClasses/{custom_class}".format( project=project, location=location, custom_class=custom_class, ) @@ -3377,7 +3441,6 @@ def test_phrase_set_path(): project = "cuttlefish" location = "mussel" phrase_set = "winkle" - expected = "projects/{project}/locations/{location}/phraseSets/{phrase_set}".format( project=project, location=location, phrase_set=phrase_set, ) @@ -3400,7 +3463,6 @@ def test_parse_phrase_set_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3421,7 +3483,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = AdaptationClient.common_folder_path(folder) assert expected == actual @@ -3440,7 +3501,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = AdaptationClient.common_organization_path(organization) assert expected == actual @@ -3459,7 +3519,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = AdaptationClient.common_project_path(project) assert expected == actual @@ -3479,7 +3538,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3506,7 +3564,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AdaptationTransport, "_prep_wrapped_messages" ) as prep: client = AdaptationClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3515,6 +3573,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AdaptationClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/speech_v1p1beta1/test_speech.py b/tests/unit/gapic/speech_v1p1beta1/test_speech.py index a09a0f61..67af1f43 100644 --- a/tests/unit/gapic/speech_v1p1beta1/test_speech.py +++ b/tests/unit/gapic/speech_v1p1beta1/test_speech.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,26 +23,56 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.speech_v1p1beta1.services.speech import SpeechAsyncClient from google.cloud.speech_v1p1beta1.services.speech import SpeechClient from google.cloud.speech_v1p1beta1.services.speech import transports +from google.cloud.speech_v1p1beta1.services.speech.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.speech_v1p1beta1.services.speech.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.speech_v1p1beta1.types import cloud_speech from google.cloud.speech_v1p1beta1.types import resource from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import wrappers_pb2 as wrappers # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -86,7 +115,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SpeechClient, SpeechAsyncClient,]) def test_speech_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -101,7 +130,7 @@ def test_speech_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SpeechClient, SpeechAsyncClient,]) def test_speech_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_speech_client_get_transport_class(): def test_speech_client_client_options(client_class, transport_class, transport_name): # Check that if channel is provided we won't create a new one. with mock.patch.object(SpeechClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -416,7 +445,7 @@ def test_speech_client_client_options_from_dict(): def test_recognize(transport: str = "grpc", request_type=cloud_speech.RecognizeRequest): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -427,17 +456,14 @@ def test_recognize(transport: str = "grpc", request_type=cloud_speech.RecognizeR with mock.patch.object(type(client.transport.recognize), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloud_speech.RecognizeResponse() - response = client.recognize(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.RecognizeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, cloud_speech.RecognizeResponse) @@ -449,7 +475,7 @@ def test_recognize_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -457,7 +483,6 @@ def test_recognize_empty_call(): client.recognize() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.RecognizeRequest() @@ -466,7 +491,7 @@ async def test_recognize_async( transport: str = "grpc_asyncio", request_type=cloud_speech.RecognizeRequest ): client = SpeechAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -479,13 +504,11 @@ async def test_recognize_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_speech.RecognizeResponse() ) - response = await client.recognize(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.RecognizeRequest() # Establish that the response is the type that we expect. @@ -498,13 +521,12 @@ async def test_recognize_async_from_dict(): def test_recognize_flattened(): - client = SpeechClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.recognize), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloud_speech.RecognizeResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.recognize( @@ -518,16 +540,14 @@ def test_recognize_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].config == cloud_speech.RecognitionConfig( encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 ) - assert args[0].audio == cloud_speech.RecognitionAudio(content=b"content_blob") def test_recognize_flattened_error(): - client = SpeechClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -543,7 +563,7 @@ def test_recognize_flattened_error(): @pytest.mark.asyncio async def test_recognize_flattened_async(): - client = SpeechAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.recognize), "__call__") as call: @@ -566,17 +586,15 @@ async def test_recognize_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].config == cloud_speech.RecognitionConfig( encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 ) - assert args[0].audio == cloud_speech.RecognitionAudio(content=b"content_blob") @pytest.mark.asyncio async def test_recognize_flattened_error_async(): - client = SpeechAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -594,7 +612,7 @@ def test_long_running_recognize( transport: str = "grpc", request_type=cloud_speech.LongRunningRecognizeRequest ): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -607,13 +625,11 @@ def test_long_running_recognize( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.long_running_recognize(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.LongRunningRecognizeRequest() # Establish that the response is the type that we expect. @@ -628,7 +644,7 @@ def test_long_running_recognize_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -638,7 +654,6 @@ def test_long_running_recognize_empty_call(): client.long_running_recognize() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.LongRunningRecognizeRequest() @@ -648,7 +663,7 @@ async def test_long_running_recognize_async( request_type=cloud_speech.LongRunningRecognizeRequest, ): client = SpeechAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -663,13 +678,11 @@ async def test_long_running_recognize_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.long_running_recognize(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_speech.LongRunningRecognizeRequest() # Establish that the response is the type that we expect. @@ -682,7 +695,7 @@ async def test_long_running_recognize_async_from_dict(): def test_long_running_recognize_flattened(): - client = SpeechClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -690,7 +703,6 @@ def test_long_running_recognize_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.long_running_recognize( @@ -704,16 +716,14 @@ def test_long_running_recognize_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].config == cloud_speech.RecognitionConfig( encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 ) - assert args[0].audio == cloud_speech.RecognitionAudio(content=b"content_blob") def test_long_running_recognize_flattened_error(): - client = SpeechClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -729,7 +739,7 @@ def test_long_running_recognize_flattened_error(): @pytest.mark.asyncio async def test_long_running_recognize_flattened_async(): - client = SpeechAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -754,17 +764,15 @@ async def test_long_running_recognize_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].config == cloud_speech.RecognitionConfig( encoding=cloud_speech.RecognitionConfig.AudioEncoding.LINEAR16 ) - assert args[0].audio == cloud_speech.RecognitionAudio(content=b"content_blob") @pytest.mark.asyncio async def test_long_running_recognize_flattened_error_async(): - client = SpeechAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -782,13 +790,12 @@ def test_streaming_recognize( transport: str = "grpc", request_type=cloud_speech.StreamingRecognizeRequest ): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -797,13 +804,11 @@ def test_streaming_recognize( ) as call: # Designate an appropriate return value for the call. call.return_value = iter([cloud_speech.StreamingRecognizeResponse()]) - response = client.streaming_recognize(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -820,13 +825,12 @@ async def test_streaming_recognize_async( transport: str = "grpc_asyncio", request_type=cloud_speech.StreamingRecognizeRequest ): client = SpeechAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -838,13 +842,11 @@ async def test_streaming_recognize_async( call.return_value.read = mock.AsyncMock( side_effect=[cloud_speech.StreamingRecognizeResponse()] ) - response = await client.streaming_recognize(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -860,16 +862,16 @@ async def test_streaming_recognize_async_from_dict(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SpeechGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SpeechGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechClient( @@ -879,7 +881,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SpeechGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechClient( @@ -890,7 +892,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SpeechGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SpeechClient(transport=transport) assert client.transport is transport @@ -899,13 +901,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SpeechGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SpeechGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -917,23 +919,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = SpeechClient(credentials=credentials.AnonymousCredentials(),) + client = SpeechClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.SpeechGrpcTransport,) def test_speech_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SpeechTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -945,7 +947,7 @@ def test_speech_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SpeechTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -965,15 +967,37 @@ def test_speech_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_speech_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.speech_v1p1beta1.services.speech.transports.SpeechTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SpeechTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_speech_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.speech_v1p1beta1.services.speech.transports.SpeechTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SpeechTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -986,19 +1010,33 @@ def test_speech_base_transport_with_credentials_file(): def test_speech_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.speech_v1p1beta1.services.speech.transports.SpeechTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SpeechTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_speech_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SpeechClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_speech_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) SpeechClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -1006,26 +1044,152 @@ def test_speech_auth_adc(): ) -def test_speech_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.SpeechGrpcTransport, transports.SpeechGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_speech_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SpeechGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.SpeechGrpcTransport, transports.SpeechGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_speech_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SpeechGrpcTransport, grpc_helpers), + (transports.SpeechGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_speech_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "speech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="speech.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SpeechGrpcTransport, grpc_helpers), + (transports.SpeechGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_speech_transport_create_channel_old_api_core(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "speech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SpeechGrpcTransport, grpc_helpers), + (transports.SpeechGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_speech_transport_create_channel_user_scopes(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "speech.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.SpeechGrpcTransport, transports.SpeechGrpcAsyncIOTransport], ) def test_speech_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1064,7 +1228,7 @@ def test_speech_grpc_transport_client_cert_source_for_mtls(transport_class): def test_speech_host_no_port(): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="speech.googleapis.com" ), @@ -1074,7 +1238,7 @@ def test_speech_host_no_port(): def test_speech_host_with_port(): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="speech.googleapis.com:8000" ), @@ -1125,9 +1289,9 @@ def test_speech_transport_channel_mtls_with_client_cert_source(transport_class): mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1200,7 +1364,7 @@ def test_speech_transport_channel_mtls_with_adc(transport_class): def test_speech_grpc_lro_client(): client = SpeechClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1213,7 +1377,7 @@ def test_speech_grpc_lro_client(): def test_speech_grpc_lro_async_client(): client = SpeechAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1228,7 +1392,6 @@ def test_custom_class_path(): project = "squid" location = "clam" custom_class = "whelk" - expected = "projects/{project}/locations/{location}/customClasses/{custom_class}".format( project=project, location=location, custom_class=custom_class, ) @@ -1253,7 +1416,6 @@ def test_phrase_set_path(): project = "cuttlefish" location = "mussel" phrase_set = "winkle" - expected = "projects/{project}/locations/{location}/phraseSets/{phrase_set}".format( project=project, location=location, phrase_set=phrase_set, ) @@ -1276,7 +1438,6 @@ def test_parse_phrase_set_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1297,7 +1458,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = SpeechClient.common_folder_path(folder) assert expected == actual @@ -1316,7 +1476,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = SpeechClient.common_organization_path(organization) assert expected == actual @@ -1335,7 +1494,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = SpeechClient.common_project_path(project) assert expected == actual @@ -1355,7 +1513,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1382,7 +1539,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SpeechTransport, "_prep_wrapped_messages" ) as prep: client = SpeechClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1391,6 +1548,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SpeechClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)