diff --git a/google/cloud/mediatranslation/__init__.py b/google/cloud/mediatranslation/__init__.py index ffa99f5..f8c78a1 100644 --- a/google/cloud/mediatranslation/__init__.py +++ b/google/cloud/mediatranslation/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,12 +14,13 @@ # limitations under the License. # -from google.cloud.mediatranslation_v1beta1.services.speech_translation_service.async_client import ( - SpeechTranslationServiceAsyncClient, -) from google.cloud.mediatranslation_v1beta1.services.speech_translation_service.client import ( SpeechTranslationServiceClient, ) +from google.cloud.mediatranslation_v1beta1.services.speech_translation_service.async_client import ( + SpeechTranslationServiceAsyncClient, +) + from google.cloud.mediatranslation_v1beta1.types.media_translation import ( StreamingTranslateSpeechConfig, ) @@ -38,8 +38,8 @@ ) __all__ = ( - "SpeechTranslationServiceAsyncClient", "SpeechTranslationServiceClient", + "SpeechTranslationServiceAsyncClient", "StreamingTranslateSpeechConfig", "StreamingTranslateSpeechRequest", "StreamingTranslateSpeechResponse", diff --git a/google/cloud/mediatranslation_v1beta1/__init__.py b/google/cloud/mediatranslation_v1beta1/__init__.py index e40bd4a..0b82590 100644 --- a/google/cloud/mediatranslation_v1beta1/__init__.py +++ b/google/cloud/mediatranslation_v1beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,18 +15,20 @@ # from .services.speech_translation_service import SpeechTranslationServiceClient +from .services.speech_translation_service import SpeechTranslationServiceAsyncClient + from .types.media_translation import StreamingTranslateSpeechConfig from .types.media_translation import StreamingTranslateSpeechRequest from .types.media_translation import StreamingTranslateSpeechResponse from .types.media_translation import StreamingTranslateSpeechResult from .types.media_translation import TranslateSpeechConfig - __all__ = ( + "SpeechTranslationServiceAsyncClient", + "SpeechTranslationServiceClient", "StreamingTranslateSpeechConfig", "StreamingTranslateSpeechRequest", "StreamingTranslateSpeechResponse", "StreamingTranslateSpeechResult", "TranslateSpeechConfig", - "SpeechTranslationServiceClient", ) diff --git a/google/cloud/mediatranslation_v1beta1/gapic_metadata.json b/google/cloud/mediatranslation_v1beta1/gapic_metadata.json new file mode 100644 index 0000000..521e3a1 --- /dev/null +++ b/google/cloud/mediatranslation_v1beta1/gapic_metadata.json @@ -0,0 +1,33 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.mediatranslation_v1beta1", + "protoPackage": "google.cloud.mediatranslation.v1beta1", + "schema": "1.0", + "services": { + "SpeechTranslationService": { + "clients": { + "grpc": { + "libraryClient": "SpeechTranslationServiceClient", + "rpcs": { + "StreamingTranslateSpeech": { + "methods": [ + "streaming_translate_speech" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SpeechTranslationServiceAsyncClient", + "rpcs": { + "StreamingTranslateSpeech": { + "methods": [ + "streaming_translate_speech" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/mediatranslation_v1beta1/services/__init__.py b/google/cloud/mediatranslation_v1beta1/services/__init__.py index 42ffdf2..4de6597 100644 --- a/google/cloud/mediatranslation_v1beta1/services/__init__.py +++ b/google/cloud/mediatranslation_v1beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/__init__.py b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/__init__.py index 914bdb8..d2a8409 100644 --- a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/__init__.py +++ b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SpeechTranslationServiceClient from .async_client import SpeechTranslationServiceAsyncClient diff --git a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/async_client.py b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/async_client.py index 23ef741..52ed49d 100644 --- a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/async_client.py +++ b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -31,15 +29,14 @@ 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.mediatranslation_v1beta1.types import media_translation -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SpeechTranslationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SpeechTranslationServiceGrpcAsyncIOTransport from .client import SpeechTranslationServiceClient @@ -59,26 +56,22 @@ class SpeechTranslationServiceAsyncClient: parse_common_billing_account_path = staticmethod( SpeechTranslationServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SpeechTranslationServiceClient.common_folder_path) parse_common_folder_path = staticmethod( SpeechTranslationServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( SpeechTranslationServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( SpeechTranslationServiceClient.parse_common_organization_path ) - common_project_path = staticmethod( SpeechTranslationServiceClient.common_project_path ) parse_common_project_path = staticmethod( SpeechTranslationServiceClient.parse_common_project_path ) - common_location_path = staticmethod( SpeechTranslationServiceClient.common_location_path ) @@ -88,7 +81,8 @@ class SpeechTranslationServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -103,7 +97,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -120,7 +114,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SpeechTranslationServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SpeechTranslationServiceTransport: The transport used by the client instance. @@ -135,12 +129,12 @@ def transport(self) -> SpeechTranslationServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SpeechTranslationServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the speech translation service client. + """Instantiates the speech translation service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -172,7 +166,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SpeechTranslationServiceClient( credentials=credentials, transport=transport, diff --git a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/client.py b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/client.py index 1444e8f..69a0fb4 100644 --- a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/client.py +++ b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -33,18 +31,17 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.mediatranslation_v1beta1.types import media_translation -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SpeechTranslationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SpeechTranslationServiceGrpcTransport from .transports.grpc_asyncio import SpeechTranslationServiceGrpcAsyncIOTransport @@ -67,7 +64,7 @@ class SpeechTranslationServiceClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[SpeechTranslationServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -90,7 +87,8 @@ class SpeechTranslationServiceClient(metaclass=SpeechTranslationServiceClientMet @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -124,7 +122,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -141,7 +140,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -160,16 +159,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SpeechTranslationServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SpeechTranslationServiceTransport: The transport used by the client instance. + SpeechTranslationServiceTransport: 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, ) @@ -182,7 +182,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 @@ -193,7 +193,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 @@ -204,7 +204,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 @@ -215,7 +215,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, ) @@ -229,12 +229,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, SpeechTranslationServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the speech translation service client. + """Instantiates the speech translation service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -289,9 +289,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: @@ -303,12 +304,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. @@ -323,8 +326,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: diff --git a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/__init__.py b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/__init__.py index c05692c..187de33 100644 --- a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/__init__.py +++ b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/base.py b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/base.py index 1b0c4e7..c803dbd 100644 --- a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/base.py +++ b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.mediatranslation_v1beta1.types import media_translation - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -37,27 +36,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class SpeechTranslationServiceTransport(abc.ABC): """Abstract transport class for SpeechTranslationService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "mediatranslation.googleapis.com" + def __init__( self, *, - host: str = "mediatranslation.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 = { @@ -116,11 +176,11 @@ def _prep_wrapped_messages(self, client_info): @property def streaming_translate_speech( self, - ) -> typing.Callable[ + ) -> Callable[ [media_translation.StreamingTranslateSpeechRequest], - typing.Union[ + Union[ media_translation.StreamingTranslateSpeechResponse, - typing.Awaitable[media_translation.StreamingTranslateSpeechResponse], + Awaitable[media_translation.StreamingTranslateSpeechResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/grpc.py b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/grpc.py index a60eb91..a010256 100644 --- a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/grpc.py +++ b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.mediatranslation_v1beta1.types import media_translation - from .base import SpeechTranslationServiceTransport, DEFAULT_CLIENT_INFO @@ -50,7 +47,7 @@ def __init__( self, *, host: str = "mediatranslation.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -64,7 +61,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -174,7 +172,7 @@ def __init__( def create_channel( cls, host: str = "mediatranslation.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -205,13 +203,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) diff --git a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/grpc_asyncio.py b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/grpc_asyncio.py index 6ca7d69..62098f8 100644 --- a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/grpc_asyncio.py +++ b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.mediatranslation_v1beta1.types import media_translation - from .base import SpeechTranslationServiceTransport, DEFAULT_CLIENT_INFO from .grpc import SpeechTranslationServiceGrpcTransport @@ -53,7 +50,7 @@ class SpeechTranslationServiceGrpcAsyncIOTransport(SpeechTranslationServiceTrans def create_channel( cls, host: str = "mediatranslation.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -80,13 +77,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -94,7 +93,7 @@ def __init__( self, *, host: str = "mediatranslation.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -108,7 +107,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + host (Optional[str]): + The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none @@ -166,7 +166,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/mediatranslation_v1beta1/types/__init__.py b/google/cloud/mediatranslation_v1beta1/types/__init__.py index ea1571e..d782b7b 100644 --- a/google/cloud/mediatranslation_v1beta1/types/__init__.py +++ b/google/cloud/mediatranslation_v1beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .media_translation import ( StreamingTranslateSpeechConfig, StreamingTranslateSpeechRequest, diff --git a/google/cloud/mediatranslation_v1beta1/types/media_translation.py b/google/cloud/mediatranslation_v1beta1/types/media_translation.py index c1fe326..afeb0ef 100644 --- a/google/cloud/mediatranslation_v1beta1/types/media_translation.py +++ b/google/cloud/mediatranslation_v1beta1/types/media_translation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.rpc import status_pb2 as status # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -45,47 +42,71 @@ class TranslateSpeechConfig(proto.Message): Uncompressed 16-bit signed little-endian samples (Linear PCM). + + - ``flac`` + + ``flac`` (Free Lossless Audio Codec) is the recommended + encoding because it is lossless--therefore recognition is + not compromised--and requires only about half the + bandwidth of ``linear16``. + + - ``mulaw`` + + 8-bit samples that compand 14-bit audio samples using + G.711 PCMU/mu-law. + + - ``amr`` + + Adaptive Multi-Rate Narrowband codec. + ``sample_rate_hertz`` must be 8000. + + - ``amr-wb`` + + Adaptive Multi-Rate Wideband codec. ``sample_rate_hertz`` + must be 16000. + + - ``ogg-opus`` + + Opus encoded audio frames in + `Ogg `__ container. + ``sample_rate_hertz`` must be one of 8000, 12000, 16000, + 24000, or 48000. + + - ``mp3`` + + MP3 audio. Support all standard MP3 bitrates (which range + from 32-320 kbps). When using this encoding, + ``sample_rate_hertz`` has to match the sample rate of the + file being used. source_language_code (str): Required. Source language code (BCP-47) of the input audio. - alternative_source_language_codes (Sequence[str]): - Optional. A list of up to 3 additional language codes - (BCP-47), listing possible alternative languages of the - supplied audio. If alternative source languages are listed, - speech translation result will translate in the most likely - language detected including the main source_language_code. - The translated result will include the language code of the - language detected in the audio. target_language_code (str): Required. Target language code (BCP-47) of the output. sample_rate_hertz (int): - Optional. Sample rate in Hertz of the audio data. Valid - values are: 8000-48000. 16000 is optimal. For best results, - set the sampling rate of the audio source to 16000 Hz. If - that's not possible, use the native sample rate of the audio - source (instead of re-sampling). This field can only be - omitted for ``FLAC`` and ``WAV`` audio files. + Optional. Sample rate in Hertz of the audio + data. Valid values are: 8000-48000. 16000 is + optimal. For best results, set the sampling rate + of the audio source to 16000 Hz. If that's not + possible, use the native sample rate of the + audio source (instead of re-sampling). model (str): - Optional. + Optional. ``google-provided-model/video`` and + ``google-provided-model/enhanced-phone-call`` are premium + models. ``google-provided-model/phone-call`` is not premium + model. """ - audio_encoding = proto.Field(proto.STRING, number=1) - - source_language_code = proto.Field(proto.STRING, number=2) - - alternative_source_language_codes = proto.RepeatedField(proto.STRING, number=6) - - target_language_code = proto.Field(proto.STRING, number=3) - - sample_rate_hertz = proto.Field(proto.INT32, number=4) - - model = proto.Field(proto.STRING, number=5) + audio_encoding = proto.Field(proto.STRING, number=1,) + source_language_code = proto.Field(proto.STRING, number=2,) + target_language_code = proto.Field(proto.STRING, number=3,) + sample_rate_hertz = proto.Field(proto.INT32, number=4,) + model = proto.Field(proto.STRING, number=5,) class StreamingTranslateSpeechConfig(proto.Message): r"""Config used for streaming translation. - Attributes: audio_config (google.cloud.mediatranslation_v1beta1.types.TranslateSpeechConfig): Required. The common config for all the @@ -115,8 +136,7 @@ class StreamingTranslateSpeechConfig(proto.Message): audio_config = proto.Field( proto.MESSAGE, number=1, message="TranslateSpeechConfig", ) - - single_utterance = proto.Field(proto.BOOL, number=2) + single_utterance = proto.Field(proto.BOOL, number=2,) class StreamingTranslateSpeechRequest(proto.Message): @@ -153,8 +173,7 @@ class StreamingTranslateSpeechRequest(proto.Message): oneof="streaming_request", message="StreamingTranslateSpeechConfig", ) - - audio_content = proto.Field(proto.BYTES, number=2, oneof="streaming_request") + audio_content = proto.Field(proto.BYTES, number=2, oneof="streaming_request",) class StreamingTranslateSpeechResult(proto.Message): @@ -164,19 +183,10 @@ class StreamingTranslateSpeechResult(proto.Message): Attributes: text_translation_result (google.cloud.mediatranslation_v1beta1.types.StreamingTranslateSpeechResult.TextTranslationResult): Text translation result. - recognition_result (str): - Output only. The debug only recognition - result in original language. This field is debug - only and will be set to empty string if not - available. This is implementation detail and - will not be backward compatible. - Still need to decide whether to expose this - field by default. """ class TextTranslationResult(proto.Message): r"""Text translation result. - Attributes: translation (str): Output only. The translated sentence. @@ -188,25 +198,15 @@ class TextTranslationResult(proto.Message): ``StreamingTranslateSpeechResult``, the streaming translator will not return any further hypotheses for this portion of the transcript and corresponding audio. - detected_source_language_code (str): - Output only. The source language code (BCP-47) detected in - the audio. Speech translation result will translate in the - most likely language detected including the alternative - source languages and main source_language_code. """ - translation = proto.Field(proto.STRING, number=1) - - is_final = proto.Field(proto.BOOL, number=2) - - detected_source_language_code = proto.Field(proto.STRING, number=3) + translation = proto.Field(proto.STRING, number=1,) + is_final = proto.Field(proto.BOOL, number=2,) text_translation_result = proto.Field( proto.MESSAGE, number=1, oneof="result", message=TextTranslationResult, ) - recognition_result = proto.Field(proto.STRING, number=3) - class StreamingTranslateSpeechResponse(proto.Message): r"""A streaming speech translation response corresponding to a @@ -230,12 +230,10 @@ class SpeechEventType(proto.Enum): SPEECH_EVENT_TYPE_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,) result = proto.Field( proto.MESSAGE, number=2, message="StreamingTranslateSpeechResult", ) - speech_event_type = proto.Field(proto.ENUM, number=3, enum=SpeechEventType,) diff --git a/scripts/fixup_mediatranslation_v1beta1_keywords.py b/scripts/fixup_mediatranslation_v1beta1_keywords.py index 8e06354..4e53c64 100644 --- a/scripts/fixup_mediatranslation_v1beta1_keywords.py +++ b/scripts/fixup_mediatranslation_v1beta1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,8 +39,7 @@ def partition( class mediatranslationCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'streaming_translate_speech': ('streaming_config', 'audio_content', ), - + 'streaming_translate_speech': ('streaming_config', 'audio_content', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -73,7 +70,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 dc2961c..32478f5 100644 --- a/setup.py +++ b/setup.py @@ -41,6 +41,7 @@ install_requires=( "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "proto-plus >= 1.10.0", + "packaging >= 14.3", ), python_requires=">=3.6", classifiers=[ diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 4595736..f0e0706 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -6,4 +6,6 @@ # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 google-api-core==1.22.2 -proto-plus==1.10.0 \ No newline at end of file +proto-plus==1.10.0 +packaging==14.3 +google-auth==1.24.0 # TODO: remove when google-auth>=1.25.0 is transitively required through google-api-core diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..4de6597 --- /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 0000000..4de6597 --- /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 0000000..4de6597 --- /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/mediatranslation_v1beta1/__init__.py b/tests/unit/gapic/mediatranslation_v1beta1/__init__.py index 42ffdf2..4de6597 100644 --- a/tests/unit/gapic/mediatranslation_v1beta1/__init__.py +++ b/tests/unit/gapic/mediatranslation_v1beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/mediatranslation_v1beta1/test_speech_translation_service.py b/tests/unit/gapic/mediatranslation_v1beta1/test_speech_translation_service.py index 56b120c..3e1dc51 100644 --- a/tests/unit/gapic/mediatranslation_v1beta1/test_speech_translation_service.py +++ b/tests/unit/gapic/mediatranslation_v1beta1/test_speech_translation_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.mediatranslation_v1beta1.services.speech_translation_service import ( SpeechTranslationServiceAsyncClient, @@ -41,9 +40,39 @@ from google.cloud.mediatranslation_v1beta1.services.speech_translation_service import ( transports, ) +from google.cloud.mediatranslation_v1beta1.services.speech_translation_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.mediatranslation_v1beta1.services.speech_translation_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.mediatranslation_v1beta1.types import media_translation 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(): @@ -96,7 +125,7 @@ def test__get_default_mtls_endpoint(): [SpeechTranslationServiceClient, SpeechTranslationServiceAsyncClient,], ) def test_speech_translation_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -114,7 +143,7 @@ def test_speech_translation_service_client_from_service_account_info(client_clas [SpeechTranslationServiceClient, SpeechTranslationServiceAsyncClient,], ) def test_speech_translation_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -173,7 +202,7 @@ def test_speech_translation_service_client_client_options( with mock.patch.object( SpeechTranslationServiceClient, "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() @@ -482,13 +511,12 @@ def test_streaming_translate_speech( request_type=media_translation.StreamingTranslateSpeechRequest, ): client = SpeechTranslationServiceClient( - 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. @@ -497,13 +525,11 @@ def test_streaming_translate_speech( ) as call: # Designate an appropriate return value for the call. call.return_value = iter([media_translation.StreamingTranslateSpeechResponse()]) - response = client.streaming_translate_speech(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. @@ -521,13 +547,12 @@ async def test_streaming_translate_speech_async( request_type=media_translation.StreamingTranslateSpeechRequest, ): client = SpeechTranslationServiceAsyncClient( - 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. @@ -539,13 +564,11 @@ async def test_streaming_translate_speech_async( call.return_value.read = mock.AsyncMock( side_effect=[media_translation.StreamingTranslateSpeechResponse()] ) - response = await client.streaming_translate_speech(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. @@ -561,16 +584,16 @@ async def test_streaming_translate_speech_async_from_dict(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SpeechTranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechTranslationServiceClient( - 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.SpeechTranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechTranslationServiceClient( @@ -580,7 +603,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SpeechTranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechTranslationServiceClient( @@ -591,7 +614,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SpeechTranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SpeechTranslationServiceClient(transport=transport) assert client.transport is transport @@ -600,13 +623,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SpeechTranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SpeechTranslationServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -621,8 +644,8 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() @@ -630,7 +653,7 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = SpeechTranslationServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) assert isinstance( client.transport, transports.SpeechTranslationServiceGrpcTransport, @@ -639,9 +662,9 @@ def test_transport_grpc_default(): def test_speech_translation_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SpeechTranslationServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -653,7 +676,7 @@ def test_speech_translation_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SpeechTranslationServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -664,15 +687,37 @@ def test_speech_translation_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_speech_translation_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( - auth, "load_credentials_from_file" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.mediatranslation_v1beta1.services.speech_translation_service.transports.SpeechTranslationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SpeechTranslationServiceTransport( + 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_translation_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.mediatranslation_v1beta1.services.speech_translation_service.transports.SpeechTranslationServiceTransport._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.SpeechTranslationServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -685,19 +730,33 @@ def test_speech_translation_service_base_transport_with_credentials_file(): def test_speech_translation_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.mediatranslation_v1beta1.services.speech_translation_service.transports.SpeechTranslationServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SpeechTranslationServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_speech_translation_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SpeechTranslationServiceClient() + 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_translation_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) SpeechTranslationServiceClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -705,20 +764,158 @@ def test_speech_translation_service_auth_adc(): ) -def test_speech_translation_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SpeechTranslationServiceGrpcTransport, + transports.SpeechTranslationServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_speech_translation_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SpeechTranslationServiceGrpcTransport( - 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.SpeechTranslationServiceGrpcTransport, + transports.SpeechTranslationServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_speech_translation_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SpeechTranslationServiceGrpcTransport, grpc_helpers), + (transports.SpeechTranslationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_speech_translation_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "mediatranslation.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="mediatranslation.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.SpeechTranslationServiceGrpcTransport, grpc_helpers), + (transports.SpeechTranslationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_speech_translation_service_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "mediatranslation.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.SpeechTranslationServiceGrpcTransport, grpc_helpers), + (transports.SpeechTranslationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_speech_translation_service_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "mediatranslation.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", [ @@ -729,7 +926,7 @@ def test_speech_translation_service_transport_auth_adc(): def test_speech_translation_service_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -768,7 +965,7 @@ def test_speech_translation_service_grpc_transport_client_cert_source_for_mtls( def test_speech_translation_service_host_no_port(): client = SpeechTranslationServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="mediatranslation.googleapis.com" ), @@ -778,7 +975,7 @@ def test_speech_translation_service_host_no_port(): def test_speech_translation_service_host_with_port(): client = SpeechTranslationServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="mediatranslation.googleapis.com:8000" ), @@ -834,9 +1031,9 @@ def test_speech_translation_service_transport_channel_mtls_with_client_cert_sour 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", @@ -912,7 +1109,6 @@ def test_speech_translation_service_transport_channel_mtls_with_adc(transport_cl def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -933,7 +1129,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = SpeechTranslationServiceClient.common_folder_path(folder) assert expected == actual @@ -952,7 +1147,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = SpeechTranslationServiceClient.common_organization_path(organization) assert expected == actual @@ -971,7 +1165,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = SpeechTranslationServiceClient.common_project_path(project) assert expected == actual @@ -991,7 +1184,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, ) @@ -1018,7 +1210,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SpeechTranslationServiceTransport, "_prep_wrapped_messages" ) as prep: client = SpeechTranslationServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1027,6 +1219,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SpeechTranslationServiceClient.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)