- On January 1, 2020 this library will no longer support Python 2 on the latest released version. - Previously released library versions will continue to be available. For more information please + As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please visit Python 2 support on Google Cloud.
{% block body %} {% endblock %} diff --git a/docs/conf.py b/docs/conf.py index 8302259..5a9caee 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,12 +20,16 @@ # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("..")) +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + __version__ = "" # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" +needs_sphinx = "1.5.5" # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom @@ -35,6 +39,7 @@ "sphinx.ext.autosummary", "sphinx.ext.intersphinx", "sphinx.ext.coverage", + "sphinx.ext.doctest", "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", @@ -43,7 +48,7 @@ # autodoc/autosummary flags autoclass_content = "both" -autodoc_default_flags = ["members"] +autodoc_default_options = {"members": True} autosummary_generate = True @@ -90,7 +95,12 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ["_build"] +exclude_patterns = [ + "_build", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -335,10 +345,11 @@ # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), } 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 5114329..914bdb8 100644 --- a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/__init__.py +++ b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/__init__.py @@ -18,4 +18,7 @@ from .client import SpeechTranslationServiceClient from .async_client import SpeechTranslationServiceAsyncClient -__all__ = ("SpeechTranslationServiceClient", "SpeechTranslationServiceAsyncClient") +__all__ = ( + "SpeechTranslationServiceClient", + "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 d6b5d1d..79df893 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 @@ -193,12 +193,12 @@ def streaming_translate_speech( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.streaming_translate_speech, - default_timeout=None, + default_timeout=400.0, client_info=DEFAULT_CLIENT_INFO, ) # Send the request. - response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -207,8 +207,8 @@ def streaming_translate_speech( try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( - "google-cloud-media-translation" - ).version + "google-cloud-media-translation", + ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() 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 635b223..dc7b1a1 100644 --- a/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/client.py +++ b/google/cloud/mediatranslation_v1beta1/services/speech_translation_service/client.py @@ -65,7 +65,7 @@ class SpeechTranslationServiceClientMeta(type): _transport_registry["grpc_asyncio"] = SpeechTranslationServiceGrpcAsyncIOTransport def get_transport_class( - cls, label: str = None + cls, label: str = None, ) -> Type[SpeechTranslationServiceTransport]: """Return an appropriate transport class. @@ -155,7 +155,7 @@ def transport(self) -> SpeechTranslationServiceTransport: def common_billing_account_path(billing_account: str,) -> str: """Return a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( - billing_account=billing_account + billing_account=billing_account, ) @staticmethod @@ -167,7 +167,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.""" - return "folders/{folder}".format(folder=folder) + return "folders/{folder}".format(folder=folder,) @staticmethod def parse_common_folder_path(path: str) -> Dict[str, str]: @@ -178,7 +178,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.""" - return "organizations/{organization}".format(organization=organization) + return "organizations/{organization}".format(organization=organization,) @staticmethod def parse_common_organization_path(path: str) -> Dict[str, str]: @@ -189,7 +189,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.""" - return "projects/{project}".format(project=project) + return "projects/{project}".format(project=project,) @staticmethod def parse_common_project_path(path: str) -> Dict[str, str]: @@ -198,10 +198,10 @@ def parse_common_project_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def common_location_path(project: str, location: str) -> str: + def common_location_path(project: str, location: str,) -> str: """Return a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( - project=project, location=location + project=project, location=location, ) @staticmethod @@ -370,7 +370,7 @@ def streaming_translate_speech( ] # Send the request. - response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -379,8 +379,8 @@ def streaming_translate_speech( try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( - "google-cloud-media-translation" - ).version + "google-cloud-media-translation", + ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() 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 eb6e39d..8957b07 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 @@ -31,8 +31,8 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( - "google-cloud-media-translation" - ).version + "google-cloud-media-translation", + ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -108,14 +108,14 @@ def _prep_wrapped_messages(self, client_info): self._wrapped_methods = { self.streaming_translate_speech: gapic_v1.method.wrap_method( self.streaming_translate_speech, - default_timeout=None, + default_timeout=400.0, client_info=client_info, - ) + ), } @property def streaming_translate_speech( - self + self, ) -> typing.Callable[ [media_translation.StreamingTranslateSpeechRequest], typing.Union[ 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 65d3d14..63175e5 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 @@ -146,6 +146,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -164,6 +168,10 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._stubs = {} # type: Dict[str, Callable] @@ -231,7 +239,7 @@ def grpc_channel(self) -> grpc.Channel: @property def streaming_translate_speech( - self + self, ) -> Callable[ [media_translation.StreamingTranslateSpeechRequest], media_translation.StreamingTranslateSpeechResponse, 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 d015b8f..de9258e 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 @@ -191,6 +191,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -209,6 +213,10 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) # Run the base constructor. @@ -235,7 +243,7 @@ def grpc_channel(self) -> aio.Channel: @property def streaming_translate_speech( - self + self, ) -> Callable[ [media_translation.StreamingTranslateSpeechRequest], Awaitable[media_translation.StreamingTranslateSpeechResponse], diff --git a/google/cloud/mediatranslation_v1beta1/types/media_translation.py b/google/cloud/mediatranslation_v1beta1/types/media_translation.py index 8d59766..ccb1a61 100644 --- a/google/cloud/mediatranslation_v1beta1/types/media_translation.py +++ b/google/cloud/mediatranslation_v1beta1/types/media_translation.py @@ -112,7 +112,9 @@ class StreamingTranslateSpeechConfig(proto.Message): previous response is true). """ - audio_config = proto.Field(proto.MESSAGE, number=1, message="TranslateSpeechConfig") + audio_config = proto.Field( + proto.MESSAGE, number=1, message="TranslateSpeechConfig", + ) single_utterance = proto.Field(proto.BOOL, number=2) @@ -200,7 +202,7 @@ class TextTranslationResult(proto.Message): detected_source_language_code = proto.Field(proto.STRING, number=3) text_translation_result = proto.Field( - proto.MESSAGE, number=1, oneof="result", message=TextTranslationResult + proto.MESSAGE, number=1, oneof="result", message=TextTranslationResult, ) recognition_result = proto.Field(proto.STRING, number=3) @@ -228,13 +230,13 @@ 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.Status,) result = proto.Field( - proto.MESSAGE, number=2, message="StreamingTranslateSpeechResult" + proto.MESSAGE, number=2, message="StreamingTranslateSpeechResult", ) - speech_event_type = proto.Field(proto.ENUM, number=3, enum=SpeechEventType) + speech_event_type = proto.Field(proto.ENUM, number=3, enum=SpeechEventType,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/noxfile.py b/noxfile.py index 2102879..8004482 100644 --- a/noxfile.py +++ b/noxfile.py @@ -23,14 +23,15 @@ import nox -BLACK_VERSION = "black==19.3b0" +BLACK_VERSION = "black==19.10b0" BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] -if os.path.exists("samples"): - BLACK_PATHS.append("samples") +DEFAULT_PYTHON_VERSION = "3.8" +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] -@nox.session(python="3.7") +@nox.session(python=DEFAULT_PYTHON_VERSION) def lint(session): """Run linters. @@ -38,7 +39,9 @@ def lint(session): serious code quality issues. """ session.install("flake8", BLACK_VERSION) - session.run("black", "--check", *BLACK_PATHS) + session.run( + "black", "--check", *BLACK_PATHS, + ) session.run("flake8", "google", "tests") @@ -53,10 +56,12 @@ def blacken(session): check the state of the `gcp_ubuntu_config` we use for that Kokoro run. """ session.install(BLACK_VERSION) - session.run("black", *BLACK_PATHS) + session.run( + "black", *BLACK_PATHS, + ) -@nox.session(python="3.7") +@nox.session(python=DEFAULT_PYTHON_VERSION) def lint_setup_py(session): """Verify that setup.py is valid (including RST check).""" session.install("docutils", "pygments") @@ -65,16 +70,19 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. - session.install("mock", "pytest", "pytest-cov") + session.install("asyncmock", "pytest-asyncio") + + session.install( + "mock", "pytest", "pytest-cov", + ) session.install("-e", ".") # Run py.test against the unit tests. session.run( "py.test", "--quiet", - "--cov=google.cloud.mediatranslation", - "--cov=google.cloud", - "--cov=tests.unit", + "--cov=google/cloud", + "--cov=tests/unit", "--cov-append", "--cov-config=.coveragerc", "--cov-report=", @@ -84,17 +92,21 @@ def default(session): ) -@nox.session(python=["3.6", "3.7", "3.8"]) +@nox.session(python=UNIT_TEST_PYTHON_VERSIONS) def unit(session): """Run the unit test suite.""" default(session) -@nox.session(python=["3.7"]) +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) def system(session): """Run the system test suite.""" system_test_path = os.path.join("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") # Sanity check: Only run tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable") @@ -110,7 +122,9 @@ def system(session): # Install all test dependencies, then install this package into the # virtualenv's dist-packages. - session.install("mock", "pytest", "google-cloud-testutils") + session.install( + "mock", "pytest", "google-cloud-testutils", + ) session.install("-e", ".") # Run py.test against the system tests. @@ -120,7 +134,7 @@ def system(session): session.run("py.test", "--quiet", system_test_folder_path, *session.posargs) -@nox.session(python="3.7") +@nox.session(python=DEFAULT_PYTHON_VERSION) def cover(session): """Run the final coverage report. @@ -133,7 +147,7 @@ def cover(session): session.run("coverage", "erase") -@nox.session(python="3.7") +@nox.session(python=DEFAULT_PYTHON_VERSION) def docs(session): """Build the docs for this library.""" @@ -153,3 +167,38 @@ def docs(session): os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + # sphinx-docfx-yaml supports up to sphinx version 1.5.5. + # https://github.com/docascode/sphinx-docfx-yaml/issues/97 + session.install("sphinx==1.5.5", "alabaster", "recommonmark", "sphinx-docfx-yaml") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/scripts/decrypt-secrets.sh b/scripts/decrypt-secrets.sh new file mode 100755 index 0000000..21f6d2a --- /dev/null +++ b/scripts/decrypt-secrets.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Copyright 2015 Google Inc. All rights reserved. +# +# 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. + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +ROOT=$( dirname "$DIR" ) + +# Work from the project root. +cd $ROOT + +# Prevent it from overriding files. +# We recommend that sample authors use their own service account files and cloud project. +# In that case, they are supposed to prepare these files by themselves. +if [[ -f "testing/test-env.sh" ]] || \ + [[ -f "testing/service-account.json" ]] || \ + [[ -f "testing/client-secrets.json" ]]; then + echo "One or more target files exist, aborting." + exit 1 +fi + +# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. +PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" + +gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ + --project="${PROJECT_ID}" \ + > testing/test-env.sh +gcloud secrets versions access latest \ + --secret="python-docs-samples-service-account" \ + --project="${PROJECT_ID}" \ + > testing/service-account.json +gcloud secrets versions access latest \ + --secret="python-docs-samples-client-secrets" \ + --project="${PROJECT_ID}" \ + > testing/client-secrets.json diff --git a/scripts/readme-gen/readme_gen.py b/scripts/readme-gen/readme_gen.py new file mode 100644 index 0000000..d309d6e --- /dev/null +++ b/scripts/readme-gen/readme_gen.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +# Copyright 2016 Google Inc +# +# 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. + +"""Generates READMEs using configuration defined in yaml.""" + +import argparse +import io +import os +import subprocess + +import jinja2 +import yaml + + +jinja_env = jinja2.Environment( + trim_blocks=True, + loader=jinja2.FileSystemLoader( + os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates')))) + +README_TMPL = jinja_env.get_template('README.tmpl.rst') + + +def get_help(file): + return subprocess.check_output(['python', file, '--help']).decode() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('source') + parser.add_argument('--destination', default='README.rst') + + args = parser.parse_args() + + source = os.path.abspath(args.source) + root = os.path.dirname(source) + destination = os.path.join(root, args.destination) + + jinja_env.globals['get_help'] = get_help + + with io.open(source, 'r') as f: + config = yaml.load(f) + + # This allows get_help to execute in the right directory. + os.chdir(root) + + output = README_TMPL.render(config) + + with io.open(destination, 'w') as f: + f.write(output) + + +if __name__ == '__main__': + main() diff --git a/scripts/readme-gen/templates/README.tmpl.rst b/scripts/readme-gen/templates/README.tmpl.rst new file mode 100644 index 0000000..4fd2397 --- /dev/null +++ b/scripts/readme-gen/templates/README.tmpl.rst @@ -0,0 +1,87 @@ +{# The following line is a lie. BUT! Once jinja2 is done with it, it will + become truth! #} +.. This file is automatically generated. Do not edit this file directly. + +{{product.name}} Python Samples +=============================================================================== + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/README.rst + + +This directory contains samples for {{product.name}}. {{product.description}} + +{{description}} + +.. _{{product.name}}: {{product.url}} + +{% if required_api_url %} +To run the sample, you need to enable the API at: {{required_api_url}} +{% endif %} + +{% if required_role %} +To run the sample, you need to have `{{required_role}}` role. +{% endif %} + +{{other_required_steps}} + +{% if setup %} +Setup +------------------------------------------------------------------------------- + +{% for section in setup %} + +{% include section + '.tmpl.rst' %} + +{% endfor %} +{% endif %} + +{% if samples %} +Samples +------------------------------------------------------------------------------- + +{% for sample in samples %} +{{sample.name}} ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +{% if not sample.hide_cloudshell_button %} +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/{{sample.file}},{{folder}}/README.rst +{% endif %} + + +{{sample.description}} + +To run this sample: + +.. code-block:: bash + + $ python {{sample.file}} +{% if sample.show_help %} + + {{get_help(sample.file)|indent}} +{% endif %} + + +{% endfor %} +{% endif %} + +{% if cloud_client_library %} + +The client library +------------------------------------------------------------------------------- + +This sample uses the `Google Cloud Client Library for Python`_. +You can read the documentation for more details on API usage and use GitHub +to `browse the source`_ and `report issues`_. + +.. _Google Cloud Client Library for Python: + https://googlecloudplatform.github.io/google-cloud-python/ +.. _browse the source: + https://github.com/GoogleCloudPlatform/google-cloud-python +.. _report issues: + https://github.com/GoogleCloudPlatform/google-cloud-python/issues + +{% endif %} + +.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/scripts/readme-gen/templates/auth.tmpl.rst b/scripts/readme-gen/templates/auth.tmpl.rst new file mode 100644 index 0000000..1446b94 --- /dev/null +++ b/scripts/readme-gen/templates/auth.tmpl.rst @@ -0,0 +1,9 @@ +Authentication +++++++++++++++ + +This sample requires you to have authentication setup. Refer to the +`Authentication Getting Started Guide`_ for instructions on setting up +credentials for applications. + +.. _Authentication Getting Started Guide: + https://cloud.google.com/docs/authentication/getting-started diff --git a/scripts/readme-gen/templates/auth_api_key.tmpl.rst b/scripts/readme-gen/templates/auth_api_key.tmpl.rst new file mode 100644 index 0000000..11957ce --- /dev/null +++ b/scripts/readme-gen/templates/auth_api_key.tmpl.rst @@ -0,0 +1,14 @@ +Authentication +++++++++++++++ + +Authentication for this service is done via an `API Key`_. To obtain an API +Key: + +1. Open the `Cloud Platform Console`_ +2. Make sure that billing is enabled for your project. +3. From the **Credentials** page, create a new **API Key** or use an existing + one for your project. + +.. _API Key: + https://developers.google.com/api-client-library/python/guide/aaa_apikeys +.. _Cloud Console: https://console.cloud.google.com/project?_ diff --git a/scripts/readme-gen/templates/install_deps.tmpl.rst b/scripts/readme-gen/templates/install_deps.tmpl.rst new file mode 100644 index 0000000..a0406db --- /dev/null +++ b/scripts/readme-gen/templates/install_deps.tmpl.rst @@ -0,0 +1,29 @@ +Install Dependencies +++++++++++++++++++++ + +#. Clone python-docs-samples and change directory to the sample directory you want to use. + + .. code-block:: bash + + $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git + +#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. + + .. _Python Development Environment Setup Guide: + https://cloud.google.com/python/setup + +#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. + + .. code-block:: bash + + $ virtualenv env + $ source env/bin/activate + +#. Install the dependencies needed to run the samples. + + .. code-block:: bash + + $ pip install -r requirements.txt + +.. _pip: https://pip.pypa.io/ +.. _virtualenv: https://virtualenv.pypa.io/ diff --git a/scripts/readme-gen/templates/install_portaudio.tmpl.rst b/scripts/readme-gen/templates/install_portaudio.tmpl.rst new file mode 100644 index 0000000..5ea33d1 --- /dev/null +++ b/scripts/readme-gen/templates/install_portaudio.tmpl.rst @@ -0,0 +1,35 @@ +Install PortAudio ++++++++++++++++++ + +Install `PortAudio`_. This is required by the `PyAudio`_ library to stream +audio from your computer's microphone. PyAudio depends on PortAudio for cross-platform compatibility, and is installed differently depending on the +platform. + +* For Mac OS X, you can use `Homebrew`_:: + + brew install portaudio + + **Note**: if you encounter an error when running `pip install` that indicates + it can't find `portaudio.h`, try running `pip install` with the following + flags:: + + pip install --global-option='build_ext' \ + --global-option='-I/usr/local/include' \ + --global-option='-L/usr/local/lib' \ + pyaudio + +* For Debian / Ubuntu Linux:: + + apt-get install portaudio19-dev python-all-dev + +* Windows may work without having to install PortAudio explicitly (it will get + installed with PyAudio). + +For more details, see the `PyAudio installation`_ page. + + +.. _PyAudio: https://people.csail.mit.edu/hubert/pyaudio/ +.. _PortAudio: http://www.portaudio.com/ +.. _PyAudio installation: + https://people.csail.mit.edu/hubert/pyaudio/#downloads +.. _Homebrew: http://brew.sh diff --git a/setup.py b/setup.py index 5d161ed..3b081ff 100644 --- a/setup.py +++ b/setup.py @@ -39,8 +39,8 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - "google-api-core[grpc] >= 1.17.0, < 2.0.0dev", - "proto-plus >= 0.4.0", + "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", + "proto-plus >= 1.10.0", ), python_requires=">=3.6", setup_requires=["libcst >= 0.2.5"], diff --git a/synth.metadata b/synth.metadata index f7082d2..e4376ee 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,22 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-media-translation.git", - "sha": "b0f04ad867e44ce270a3c873df9652b85776b97a" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "eafa840ceec23b44a5c21670288107c661252711", - "internalRef": "313488995" + "remote": "git@github.com:googleapis/python-media-translation", + "sha": "55eb3dc6052f53a4d192cc4b6fd41bc415c9d304" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "71b8a272549c06b5768d00fa48d3ae990e871bec" + "sha": "6b026e1443948dcfc0b9e3289c85e940eb70f694" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "71b8a272549c06b5768d00fa48d3ae990e871bec" + "sha": "6b026e1443948dcfc0b9e3289c85e940eb70f694" } } ], @@ -37,62 +29,8 @@ "apiName": "mediatranslation", "apiVersion": "v1beta1", "language": "python", - "generator": "gapic-generator-python" + "generator": "bazel" } } - ], - "generatedFiles": [ - ".coveragerc", - ".flake8", - ".github/CONTRIBUTING.md", - ".github/ISSUE_TEMPLATE/bug_report.md", - ".github/ISSUE_TEMPLATE/feature_request.md", - ".github/ISSUE_TEMPLATE/support_request.md", - ".github/PULL_REQUEST_TEMPLATE.md", - ".github/release-please.yml", - ".gitignore", - ".kokoro/build.sh", - ".kokoro/continuous/common.cfg", - ".kokoro/continuous/continuous.cfg", - ".kokoro/docs/common.cfg", - ".kokoro/docs/docs.cfg", - ".kokoro/presubmit/common.cfg", - ".kokoro/presubmit/presubmit.cfg", - ".kokoro/publish-docs.sh", - ".kokoro/release.sh", - ".kokoro/release/common.cfg", - ".kokoro/release/release.cfg", - ".kokoro/trampoline.sh", - "CODE_OF_CONDUCT.md", - "CONTRIBUTING.rst", - "LICENSE", - "MANIFEST.in", - "docs/_static/custom.css", - "docs/_templates/layout.html", - "docs/conf.py", - "docs/mediatranslation_v1beta1/services.rst", - "docs/mediatranslation_v1beta1/types.rst", - "docs/multiprocessing.rst", - "google/cloud/mediatranslation/__init__.py", - "google/cloud/mediatranslation/py.typed", - "google/cloud/mediatranslation_v1beta1/__init__.py", - "google/cloud/mediatranslation_v1beta1/py.typed", - "google/cloud/mediatranslation_v1beta1/services/__init__.py", - "google/cloud/mediatranslation_v1beta1/services/speech_translation_service/__init__.py", - "google/cloud/mediatranslation_v1beta1/services/speech_translation_service/async_client.py", - "google/cloud/mediatranslation_v1beta1/services/speech_translation_service/client.py", - "google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/__init__.py", - "google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/base.py", - "google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/grpc.py", - "google/cloud/mediatranslation_v1beta1/services/speech_translation_service/transports/grpc_asyncio.py", - "google/cloud/mediatranslation_v1beta1/types/__init__.py", - "google/cloud/mediatranslation_v1beta1/types/media_translation.py", - "mypy.ini", - "noxfile.py", - "renovate.json", - "scripts/fixup_mediatranslation_v1beta1_keywords.py", - "setup.cfg", - "tests/unit/gapic/mediatranslation_v1beta1/__init__.py", - "tests/unit/gapic/mediatranslation_v1beta1/test_speech_translation_service.py" ] } \ No newline at end of file diff --git a/synth.py b/synth.py index 1288852..9d7cc96 100644 --- a/synth.py +++ b/synth.py @@ -19,41 +19,39 @@ import synthtool.gcp as gcp from synthtool.languages import python -gapic = gcp.GAPICMicrogenerator() +gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() # ---------------------------------------------------------------------------- # Generate media translation GAPIC layer # ---------------------------------------------------------------------------- -library = gapic.py_library( - "mediatranslation", "v1beta1" -) + +versions = ["v1beta1"] + +for version in versions: + library = gapic.py_library( + service="mediatranslation", + version="v1beta1", + bazel_target=f"//google/cloud/mediatranslation/{version}:mediatranslation-{version}-py", + ) s.move(library, excludes=["nox.py", "setup.py", "README.rst", "docs/index.rst"]) -# correct license headers -python.fix_pb2_headers() -python.fix_pb2_grpc_headers() -# rename library to google-cloud-service-directory -s.replace(["google/**/*.py", "tests/**/*.py"], "google-cloud-mediatranslation", "google-cloud-media-translation") +# rename library to google-cloud-media-translation +s.replace( + ["google/**/*.py", "tests/**/*.py"], + "google-cloud-mediatranslation", + "google-cloud-media-translation", +) # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=100) -s.move(templated_files, excludes=[".coveragerc"]) # the microgenerator has a good coveragerc file -s.replace(".gitignore", "bigquery/docs/generated", "htmlcov") # temporary hack to ignore htmlcov - -# Remove 2.7 and 3.5 tests from noxfile.py -s.replace("noxfile.py", '''\["2\.7", ''', '[') -s.replace("noxfile.py", '''"3.5", ''', '') - -# Expand flake errors permitted to accomodate the Microgenerator -# TODO: remove extra error codes once issues below are resolved -# F401: https://github.com/googleapis/gapic-generator-python/issues/324 -# F841: local variable 'client'/'response' is assigned to but never use -s.replace(".flake8", "ignore = .*", "ignore = E203, E266, E501, W503, F401, F841") +templated_files = common.py_library(cov_level=100, microgenerator=True) +s.move( + templated_files, excludes=[".coveragerc"] +) # the microgenerator has a good coveragerc file -s.shell.run(["nox", "-s", "blacken"], hide_output=False) \ No newline at end of file +s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/testing/.gitignore b/testing/.gitignore new file mode 100644 index 0000000..b05fbd6 --- /dev/null +++ b/testing/.gitignore @@ -0,0 +1,3 @@ +test-env.sh +service-account.json +client-secrets.json \ No newline at end of file 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 655bf07..a4993cf 100644 --- a/tests/unit/gapic/mediatranslation_v1beta1/test_speech_translation_service.py +++ b/tests/unit/gapic/mediatranslation_v1beta1/test_speech_translation_service.py @@ -403,7 +403,7 @@ def test_speech_translation_service_client_client_options_scopes( client_class, transport_class, transport_name ): # Check the case scopes are provided. - options = client_options.ClientOptions(scopes=["1", "2"]) + options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) @@ -476,7 +476,7 @@ def test_streaming_translate_speech( request_type=media_translation.StreamingTranslateSpeechRequest, ): client = SpeechTranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport + credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -515,7 +515,7 @@ async def test_streaming_translate_speech_async( request_type=media_translation.StreamingTranslateSpeechRequest, ): client = SpeechTranslationServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport + credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -555,36 +555,37 @@ 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=credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechTranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport + credentials=credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SpeechTranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechTranslationServiceClient( - client_options={"credentials_file": "credentials.json"}, transport=transport + client_options={"credentials_file": "credentials.json"}, + transport=transport, ) # It is an error to provide scopes and a transport instance. transport = transports.SpeechTranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SpeechTranslationServiceClient( - client_options={"scopes": ["1", "2"]}, transport=transport + client_options={"scopes": ["1", "2"]}, transport=transport, ) def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SpeechTranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), ) client = SpeechTranslationServiceClient(transport=transport) assert client.transport is transport @@ -593,13 +594,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=credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SpeechTranslationServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -623,10 +624,10 @@ 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=credentials.AnonymousCredentials(), ) assert isinstance( - client.transport, transports.SpeechTranslationServiceGrpcTransport + client.transport, transports.SpeechTranslationServiceGrpcTransport, ) @@ -646,7 +647,7 @@ def test_speech_translation_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SpeechTranslationServiceTransport( - credentials=credentials.AnonymousCredentials() + credentials=credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -667,7 +668,7 @@ def test_speech_translation_service_base_transport_with_credentials_file(): Transport.return_value = None load_creds.return_value = (credentials.AnonymousCredentials(), None) transport = transports.SpeechTranslationServiceTransport( - credentials_file="credentials.json", quota_project_id="octopus" + credentials_file="credentials.json", quota_project_id="octopus", ) load_creds.assert_called_once_with( "credentials.json", @@ -737,7 +738,7 @@ def test_speech_translation_service_grpc_transport_channel(): # Check that channel is used if provided. transport = transports.SpeechTranslationServiceGrpcTransport( - host="squid.clam.whelk", channel=channel + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -749,7 +750,7 @@ def test_speech_translation_service_grpc_asyncio_transport_channel(): # Check that channel is used if provided. transport = transports.SpeechTranslationServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", channel=channel + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -764,7 +765,7 @@ def test_speech_translation_service_grpc_asyncio_transport_channel(): ], ) def test_speech_translation_service_transport_channel_mtls_with_client_cert_source( - transport_class + transport_class, ): with mock.patch( "grpc.ssl_channel_credentials", autospec=True @@ -799,6 +800,10 @@ def test_speech_translation_service_transport_channel_mtls_with_client_cert_sour scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel assert transport._ssl_channel_credentials == mock_ssl_cred @@ -840,6 +845,10 @@ def test_speech_translation_service_transport_channel_mtls_with_adc(transport_cl scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel @@ -848,14 +857,16 @@ def test_common_billing_account_path(): billing_account = "squid" expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account + billing_account=billing_account, ) actual = SpeechTranslationServiceClient.common_billing_account_path(billing_account) assert expected == actual def test_parse_common_billing_account_path(): - expected = {"billing_account": "clam"} + expected = { + "billing_account": "clam", + } path = SpeechTranslationServiceClient.common_billing_account_path(**expected) # Check that the path construction is reversible. @@ -866,13 +877,15 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder) + expected = "folders/{folder}".format(folder=folder,) actual = SpeechTranslationServiceClient.common_folder_path(folder) assert expected == actual def test_parse_common_folder_path(): - expected = {"folder": "octopus"} + expected = { + "folder": "octopus", + } path = SpeechTranslationServiceClient.common_folder_path(**expected) # Check that the path construction is reversible. @@ -883,13 +896,15 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization) + expected = "organizations/{organization}".format(organization=organization,) actual = SpeechTranslationServiceClient.common_organization_path(organization) assert expected == actual def test_parse_common_organization_path(): - expected = {"organization": "nudibranch"} + expected = { + "organization": "nudibranch", + } path = SpeechTranslationServiceClient.common_organization_path(**expected) # Check that the path construction is reversible. @@ -900,13 +915,15 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project) + expected = "projects/{project}".format(project=project,) actual = SpeechTranslationServiceClient.common_project_path(project) assert expected == actual def test_parse_common_project_path(): - expected = {"project": "mussel"} + expected = { + "project": "mussel", + } path = SpeechTranslationServiceClient.common_project_path(**expected) # Check that the path construction is reversible. @@ -919,14 +936,17 @@ def test_common_location_path(): location = "nautilus" expected = "projects/{project}/locations/{location}".format( - project=project, location=location + project=project, location=location, ) actual = SpeechTranslationServiceClient.common_location_path(project, location) assert expected == actual def test_parse_common_location_path(): - expected = {"project": "scallop", "location": "abalone"} + expected = { + "project": "scallop", + "location": "abalone", + } path = SpeechTranslationServiceClient.common_location_path(**expected) # Check that the path construction is reversible. @@ -941,7 +961,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SpeechTranslationServiceTransport, "_prep_wrapped_messages" ) as prep: client = SpeechTranslationServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info + credentials=credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -950,6 +970,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=credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/mediatranslation_v1beta1/test_speech_translation_service.py b/tests/unit/mediatranslation_v1beta1/test_speech_translation_service.py deleted file mode 100644 index 966755f..0000000 --- a/tests/unit/mediatranslation_v1beta1/test_speech_translation_service.py +++ /dev/null @@ -1,367 +0,0 @@ -# -*- 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. -# - -from unittest import mock - -import grpc -import math -import pytest - -from google import auth -from google.api_core import client_options -from google.api_core import grpc_helpers -from google.auth import credentials -from google.cloud.mediatranslation_v1beta1.services.speech_translation_service import ( - SpeechTranslationServiceClient, -) -from google.cloud.mediatranslation_v1beta1.services.speech_translation_service import ( - transports, -) -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 - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SpeechTranslationServiceClient._get_default_mtls_endpoint(None) is None - assert ( - SpeechTranslationServiceClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - SpeechTranslationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - SpeechTranslationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - SpeechTranslationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - SpeechTranslationServiceClient._get_default_mtls_endpoint(non_googleapi) - == non_googleapi - ) - - -def test_speech_translation_service_client_from_service_account_file(): - creds = credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: - factory.return_value = creds - client = SpeechTranslationServiceClient.from_service_account_file( - "dummy/file/path.json" - ) - assert client._transport._credentials == creds - - client = SpeechTranslationServiceClient.from_service_account_json( - "dummy/file/path.json" - ) - assert client._transport._credentials == creds - - assert client._transport._host == "mediatranslation.googleapis.com:443" - - -def test_speech_translation_service_client_client_options(): - # Check that if channel is provided we won't create a new one. - with mock.patch( - "google.cloud.mediatranslation_v1beta1.services.speech_translation_service.SpeechTranslationServiceClient.get_transport_class" - ) as gtc: - transport = transports.SpeechTranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() - ) - client = SpeechTranslationServiceClient(transport=transport) - gtc.assert_not_called() - - # Check mTLS is not triggered with empty client options. - options = client_options.ClientOptions() - with mock.patch( - "google.cloud.mediatranslation_v1beta1.services.speech_translation_service.SpeechTranslationServiceClient.get_transport_class" - ) as gtc: - transport = gtc.return_value = mock.MagicMock() - client = SpeechTranslationServiceClient(client_options=options) - transport.assert_called_once_with( - credentials=None, host=client.DEFAULT_ENDPOINT - ) - - # Check mTLS is not triggered if api_endpoint is provided but - # client_cert_source is None. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch( - "google.cloud.mediatranslation_v1beta1.services.speech_translation_service.transports.SpeechTranslationServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = SpeechTranslationServiceClient(client_options=options) - grpc_transport.assert_called_once_with( - api_mtls_endpoint=None, - client_cert_source=None, - credentials=None, - host="squid.clam.whelk", - ) - - # Check mTLS is triggered if client_cert_source is provided. - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch( - "google.cloud.mediatranslation_v1beta1.services.speech_translation_service.transports.SpeechTranslationServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = SpeechTranslationServiceClient(client_options=options) - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=client_cert_source_callback, - credentials=None, - host=client.DEFAULT_ENDPOINT, - ) - - # Check mTLS is triggered if api_endpoint and client_cert_source are provided. - options = client_options.ClientOptions( - api_endpoint="squid.clam.whelk", client_cert_source=client_cert_source_callback - ) - with mock.patch( - "google.cloud.mediatranslation_v1beta1.services.speech_translation_service.transports.SpeechTranslationServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = SpeechTranslationServiceClient(client_options=options) - grpc_transport.assert_called_once_with( - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=client_cert_source_callback, - credentials=None, - host="squid.clam.whelk", - ) - - -def test_speech_translation_service_client_client_options_from_dict(): - with mock.patch( - "google.cloud.mediatranslation_v1beta1.services.speech_translation_service.transports.SpeechTranslationServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = SpeechTranslationServiceClient( - client_options={"api_endpoint": "squid.clam.whelk"} - ) - grpc_transport.assert_called_once_with( - api_mtls_endpoint=None, - client_cert_source=None, - credentials=None, - host="squid.clam.whelk", - ) - - -def test_streaming_translate_speech(transport: str = "grpc"): - client = SpeechTranslationServiceClient( - credentials=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 = media_translation.StreamingTranslateSpeechRequest() - - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.streaming_translate_speech), "__call__" - ) 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. - for message in response: - assert isinstance(message, media_translation.StreamingTranslateSpeechResponse) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SpeechTranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() - ) - with pytest.raises(ValueError): - client = SpeechTranslationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SpeechTranslationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() - ) - client = SpeechTranslationServiceClient(transport=transport) - assert client._transport is transport - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SpeechTranslationServiceClient( - credentials=credentials.AnonymousCredentials() - ) - assert isinstance( - client._transport, transports.SpeechTranslationServiceGrpcTransport - ) - - -def test_speech_translation_service_base_transport(): - # Instantiate the base transport. - transport = transports.SpeechTranslationServiceTransport( - credentials=credentials.AnonymousCredentials() - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ("streaming_translate_speech",) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -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) - SpeechTranslationServiceClient() - adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) - ) - - -def test_speech_translation_service_host_no_port(): - client = SpeechTranslationServiceClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="mediatranslation.googleapis.com" - ), - transport="grpc", - ) - assert client._transport._host == "mediatranslation.googleapis.com:443" - - -def test_speech_translation_service_host_with_port(): - client = SpeechTranslationServiceClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="mediatranslation.googleapis.com:8000" - ), - transport="grpc", - ) - assert client._transport._host == "mediatranslation.googleapis.com:8000" - - -def test_speech_translation_service_grpc_transport_channel(): - channel = grpc.insecure_channel("http://localhost/") - - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() - transport = transports.SpeechTranslationServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert not callback.called - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_speech_translation_service_grpc_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.SpeechTranslationServiceGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - ssl_credentials=mock_ssl_cred, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ) - assert transport.grpc_channel == mock_grpc_channel - - -@pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] -) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_speech_translation_service_grpc_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - mock_cred = mock.Mock() - transport = transports.SpeechTranslationServiceGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - ssl_credentials=mock_ssl_cred, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ) - assert transport.grpc_channel == mock_grpc_channel