From c8d6026c45ffac15e510b09530d761fc6c6c3f84 Mon Sep 17 00:00:00 2001 From: Christopher Wilcox Date: Thu, 29 Nov 2018 11:02:59 -0800 Subject: [PATCH] Blackening Continued... (#6667) * blacken bigtable * blacken logging * blacken translate * blacken runtimeconfig * blacken dns --- packages/google-cloud-translate/docs/conf.py | 173 +++++----- .../google-cloud-translate/google/__init__.py | 2 + .../google/cloud/__init__.py | 2 + .../google/cloud/translate.py | 7 +- .../google/cloud/translate_v2/__init__.py | 8 +- .../google/cloud/translate_v2/_http.py | 10 +- .../google/cloud/translate_v2/client.py | 77 +++-- .../google-cloud-translate/tests/system.py | 50 ++- .../tests/unit/test__http.py | 43 +-- .../tests/unit/test_client.py | 312 ++++++++---------- 10 files changed, 315 insertions(+), 369 deletions(-) diff --git a/packages/google-cloud-translate/docs/conf.py b/packages/google-cloud-translate/docs/conf.py index d3fbd9681138..cde7f4f9a1a7 100644 --- a/packages/google-cloud-translate/docs/conf.py +++ b/packages/google-cloud-translate/docs/conf.py @@ -18,57 +18,55 @@ # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath('..')) +sys.path.insert(0, os.path.abspath("..")) -__version__ = '0.90.4' +__version__ = "0.90.4" # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +# needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.autosummary', - 'sphinx.ext.doctest', - 'sphinx.ext.intersphinx', - 'sphinx.ext.coverage', - 'sphinx.ext.napoleon', - 'sphinx.ext.viewcode', + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.doctest", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.viewcode", ] # autodoc/autosummary flags -autoclass_content = 'both' -autodoc_default_flags = ['members'] +autoclass_content = "both" +autodoc_default_flags = ["members"] autosummary_generate = True # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # Allow markdown includes (so releases.md can include CHANGLEOG.md) # http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = { - '.md': 'recommonmark.parser.CommonMarkParser', -} +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. -#source_encoding = 'utf-8-sig' +# source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'google-cloud-translate' -copyright = u'2017, Google' -author = u'Google APIs' +project = u"google-cloud-translate" +copyright = u"2017, Google" +author = u"Google APIs" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -77,7 +75,7 @@ # The full version, including alpha/beta/rc tags. release = __version__ # The short X.Y version. -version = '.'.join(release.split('.')[0:2]) +version = ".".join(release.split(".")[0:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -88,37 +86,37 @@ # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# today_fmt = '%B %d, %Y' # 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"] # The reST default role (used for this markup: `text`) to use for all # documents. -#default_role = None +# default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] +# modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. -#keep_warnings = False +# keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True @@ -127,31 +125,31 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'alabaster' +html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -#html_theme_options = {} +# html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +# html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -#html_title = None +# html_title = None # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +# html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +# html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, @@ -161,78 +159,75 @@ # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. -#html_extra_path = [] +# html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +# html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. -#html_use_smartypants = True +# html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. -#html_domain_indices = True +# html_domain_indices = True # If false, no index is generated. -#html_use_index = True +# html_use_index = True # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +# html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -#html_search_language = 'en' +# html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value -#html_search_options = {'type': 'default'} +# html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. -#html_search_scorer = 'scorer.js' +# html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. -htmlhelp_basename = 'google-cloud-translate-doc' +htmlhelp_basename = "google-cloud-translate-doc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. #'preamble': '', - # Latex figure (float) alignment #'figure_align': 'htbp', } @@ -241,39 +236,51 @@ # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'google-cloud-translate.tex', - u'google-cloud-translate Documentation', author, 'manual'), + ( + master_doc, + "google-cloud-translate.tex", + u"google-cloud-translate Documentation", + author, + "manual", + ) ] # The name of an image file (relative to this directory) to place at the top of # the title page. -#latex_logo = None +# latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. -#latex_use_parts = False +# latex_use_parts = False # If true, show page references after internal links. -#latex_show_pagerefs = False +# latex_show_pagerefs = False # If true, show URL addresses after external links. -#latex_show_urls = False +# latex_show_urls = False # Documents to append as an appendix to all manuals. -#latex_appendices = [] +# latex_appendices = [] # If false, no module index is generated. -#latex_domain_indices = True +# latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [(master_doc, 'google-cloud-translate', - u'google-cloud-translate Documentation', [author], 1)] +man_pages = [ + ( + master_doc, + "google-cloud-translate", + u"google-cloud-translate Documentation", + [author], + 1, + ) +] # If true, show URL addresses after external links. -#man_show_urls = False +# man_show_urls = False # -- Options for Texinfo output ------------------------------------------- @@ -281,27 +288,33 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'google-cloud-translate', - u'google-cloud-translate Documentation', author, 'google-cloud-translate', - 'GAPIC library for the {metadata.shortName} v1 service', 'APIs'), + ( + master_doc, + "google-cloud-translate", + u"google-cloud-translate Documentation", + author, + "google-cloud-translate", + "GAPIC library for the {metadata.shortName} v1 service", + "APIs", + ) ] # Documents to append as an appendix to all manuals. -#texinfo_appendices = [] +# texinfo_appendices = [] # If false, no module index is generated. -#texinfo_domain_indices = True +# texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' +# texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. -#texinfo_no_detailmenu = False +# texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { - 'python': ('http://python.readthedocs.org/en/latest/', None), - 'gax': ('https://gax-python.readthedocs.org/en/latest/', None), + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), } # Napoleon settings diff --git a/packages/google-cloud-translate/google/__init__.py b/packages/google-cloud-translate/google/__init__.py index 9ee9bf4342ab..0e1bc5131ba6 100644 --- a/packages/google-cloud-translate/google/__init__.py +++ b/packages/google-cloud-translate/google/__init__.py @@ -14,7 +14,9 @@ try: import pkg_resources + pkg_resources.declare_namespace(__name__) except ImportError: import pkgutil + __path__ = pkgutil.extend_path(__path__, __name__) diff --git a/packages/google-cloud-translate/google/cloud/__init__.py b/packages/google-cloud-translate/google/cloud/__init__.py index 9ee9bf4342ab..0e1bc5131ba6 100644 --- a/packages/google-cloud-translate/google/cloud/__init__.py +++ b/packages/google-cloud-translate/google/cloud/__init__.py @@ -14,7 +14,9 @@ try: import pkg_resources + pkg_resources.declare_namespace(__name__) except ImportError: import pkgutil + __path__ = pkgutil.extend_path(__path__, __name__) diff --git a/packages/google-cloud-translate/google/cloud/translate.py b/packages/google-cloud-translate/google/cloud/translate.py index 93e1d3baaa8b..947f8c8ae093 100644 --- a/packages/google-cloud-translate/google/cloud/translate.py +++ b/packages/google-cloud-translate/google/cloud/translate.py @@ -24,9 +24,4 @@ from google.cloud.translate_v2.client import NMT -__all__ = ( - '__version__', - 'BASE', - 'Client', - 'NMT', -) +__all__ = ("__version__", "BASE", "Client", "NMT") diff --git a/packages/google-cloud-translate/google/cloud/translate_v2/__init__.py b/packages/google-cloud-translate/google/cloud/translate_v2/__init__.py index d8433c1e4eca..ba2897afbd74 100644 --- a/packages/google-cloud-translate/google/cloud/translate_v2/__init__.py +++ b/packages/google-cloud-translate/google/cloud/translate_v2/__init__.py @@ -16,12 +16,10 @@ from pkg_resources import get_distribution -__version__ = get_distribution('google-cloud-translate').version + +__version__ = get_distribution("google-cloud-translate").version from google.cloud.translate_v2.client import Client -__all__ = ( - '__version__', - 'Client', -) +__all__ = ("__version__", "Client") diff --git a/packages/google-cloud-translate/google/cloud/translate_v2/_http.py b/packages/google-cloud-translate/google/cloud/translate_v2/_http.py index bb8d19547c3c..a89ea0114a3f 100644 --- a/packages/google-cloud-translate/google/cloud/translate_v2/_http.py +++ b/packages/google-cloud-translate/google/cloud/translate_v2/_http.py @@ -29,15 +29,13 @@ class Connection(_http.JSONConnection): :param client: The client that owns the current connection. """ - API_BASE_URL = 'https://translation.googleapis.com' + API_BASE_URL = "https://translation.googleapis.com" """The base of the API call URL.""" - API_VERSION = 'v2' + API_VERSION = "v2" """The version of the API, used in building the API call's URL.""" - API_URL_TEMPLATE = '{api_base_url}/language/translate/{api_version}{path}' + API_URL_TEMPLATE = "{api_base_url}/language/translate/{api_version}{path}" """A template for the URL of a particular API call.""" - _EXTRA_HEADERS = { - _http.CLIENT_INFO_HEADER: _CLIENT_INFO, - } + _EXTRA_HEADERS = {_http.CLIENT_INFO_HEADER: _CLIENT_INFO} diff --git a/packages/google-cloud-translate/google/cloud/translate_v2/client.py b/packages/google-cloud-translate/google/cloud/translate_v2/client.py index c3cbe58eb967..f5945f793cd0 100644 --- a/packages/google-cloud-translate/google/cloud/translate_v2/client.py +++ b/packages/google-cloud-translate/google/cloud/translate_v2/client.py @@ -22,13 +22,13 @@ from google.cloud.translate_v2._http import Connection -ENGLISH_ISO_639 = 'en' +ENGLISH_ISO_639 = "en" """ISO 639-1 language code for English.""" -BASE = 'base' +BASE = "base" """Base translation model.""" -NMT = 'nmt' +NMT = "nmt" """Neural Machine Translation model.""" @@ -56,11 +56,10 @@ class Client(BaseClient): change in the future. """ - SCOPE = ('https://www.googleapis.com/auth/cloud-platform',) + SCOPE = ("https://www.googleapis.com/auth/cloud-platform",) """The scopes required for authenticating.""" - def __init__(self, target_language=ENGLISH_ISO_639, - credentials=None, _http=None): + def __init__(self, target_language=ENGLISH_ISO_639, credentials=None, _http=None): self.target_language = target_language super(Client, self).__init__(credentials=credentials, _http=_http) self._connection = Connection(self) @@ -89,10 +88,11 @@ def get_languages(self, target_language=None): if target_language is None: target_language = self.target_language if target_language is not None: - query_params['target'] = target_language + query_params["target"] = target_language response = self._connection.api_request( - method='GET', path='/languages', query_params=query_params) - return response.get('data', {}).get('languages', ()) + method="GET", path="/languages", query_params=query_params + ) + return response.get("data", {}).get("languages", ()) def detect_language(self, values): """Detect the language of a string or list of strings. @@ -128,18 +128,18 @@ def detect_language(self, values): single_value = True values = [values] - data = { - 'q': values, - } + data = {"q": values} response = self._connection.api_request( - method='POST', path='/detect', data=data) + method="POST", path="/detect", data=data + ) - detections = response.get('data', {}).get('detections', ()) + detections = response.get("data", {}).get("detections", ()) if len(values) != len(detections): - raise ValueError('Expected same number of values and detections', - values, detections) + raise ValueError( + "Expected same number of values and detections", values, detections + ) for index, value in enumerate(values): # Empirically, even clearly ambiguous text like "no" only returns @@ -148,22 +148,29 @@ def detect_language(self, values): if len(detections[index]) == 1: detections[index] = detections[index][0] else: - message = ('Expected a single detection per value, API ' - 'returned %d') % (len(detections[index]),) + message = ( + "Expected a single detection per value, API " "returned %d" + ) % (len(detections[index]),) raise ValueError(message, value, detections[index]) - detections[index]['input'] = value + detections[index]["input"] = value # The ``isReliable`` field is deprecated. - detections[index].pop('isReliable', None) + detections[index].pop("isReliable", None) if single_value: return detections[0] else: return detections - def translate(self, values, target_language=None, format_=None, - source_language=None, customization_ids=(), - model=None): + def translate( + self, + values, + target_language=None, + format_=None, + source_language=None, + customization_ids=(), + model=None, + ): """Translate a string or list of strings. See https://cloud.google.com/translate/docs/translating-text @@ -221,23 +228,23 @@ def translate(self, values, target_language=None, format_=None, customization_ids = [customization_ids] data = { - 'target': target_language, - 'q': values, - 'cid': customization_ids, - 'format': format_, - 'source': source_language, - 'model': model + "target": target_language, + "q": values, + "cid": customization_ids, + "format": format_, + "source": source_language, + "model": model, } - response = self._connection.api_request( - method='POST', path='', data=data) + response = self._connection.api_request(method="POST", path="", data=data) - translations = response.get('data', {}).get('translations', ()) + translations = response.get("data", {}).get("translations", ()) if len(values) != len(translations): - raise ValueError('Expected iterations to have same length', - values, translations) + raise ValueError( + "Expected iterations to have same length", values, translations + ) for value, translation in six.moves.zip(values, translations): - translation['input'] = value + translation["input"] = value if single_value: return translations[0] diff --git a/packages/google-cloud-translate/tests/system.py b/packages/google-cloud-translate/tests/system.py index cf6e055800cf..3daebe005134 100644 --- a/packages/google-cloud-translate/tests/system.py +++ b/packages/google-cloud-translate/tests/system.py @@ -25,6 +25,7 @@ class Config(object): This is a mutable stand-in to allow test set-up to modify global state. """ + CLIENT = None @@ -33,51 +34,44 @@ def setUpModule(): class TestTranslate(unittest.TestCase): - def test_get_languages(self): result = Config.CLIENT.get_languages() # There are **many** more than 10 languages. self.assertGreater(len(result), 10) - lang_map = {val['language']: val['name'] for val in result} - self.assertEqual(lang_map['en'], 'English') - self.assertEqual(lang_map['ja'], 'Japanese') - self.assertEqual(lang_map['lv'], 'Latvian') - self.assertEqual(lang_map['zu'], 'Zulu') + lang_map = {val["language"]: val["name"] for val in result} + self.assertEqual(lang_map["en"], "English") + self.assertEqual(lang_map["ja"], "Japanese") + self.assertEqual(lang_map["lv"], "Latvian") + self.assertEqual(lang_map["zu"], "Zulu") def test_detect_language(self): - values = ['takoy', u'fa\xe7ade', 's\'il vous plait'] + values = ["takoy", u"fa\xe7ade", "s'il vous plait"] detections = Config.CLIENT.detect_language(values) self.assertEqual(len(values), len(detections)) - self.assertEqual(detections[0]['language'], 'ru') - self.assertEqual(detections[1]['language'], 'fr') - self.assertEqual(detections[2]['language'], 'fr') + self.assertEqual(detections[0]["language"], "ru") + self.assertEqual(detections[1]["language"], "fr") + self.assertEqual(detections[2]["language"], "fr") def test_translate(self): - values = ['hvala ti', 'dankon', - 'Me llamo Jeff', 'My name is Jeff'] + values = ["hvala ti", "dankon", "Me llamo Jeff", "My name is Jeff"] translations = Config.CLIENT.translate( - values, target_language='de', model='nmt') + values, target_language="de", model="nmt" + ) self.assertEqual(len(values), len(translations)) - self.assertEqual( - translations[0]['detectedSourceLanguage'].lower(), 'hr') - self.assertEqual( - translations[0]['translatedText'].lower(), 'danke') + self.assertEqual(translations[0]["detectedSourceLanguage"].lower(), "hr") + self.assertEqual(translations[0]["translatedText"].lower(), "danke") - self.assertEqual( - translations[1]['detectedSourceLanguage'], 'eo') + self.assertEqual(translations[1]["detectedSourceLanguage"], "eo") # For some reason this is translated as both "dank" and "danke" # in a seemingly non-deterministic way. - self.assertIn( - translations[1]['translatedText'].lower(), ('dank', 'danke')) + self.assertIn(translations[1]["translatedText"].lower(), ("dank", "danke")) - self.assertEqual( - translations[2]['detectedSourceLanguage'], 'es') - self.assertEqual( - translations[2]['translatedText'].lower(), u'ich heiße jeff') + self.assertEqual(translations[2]["detectedSourceLanguage"], "es") + self.assertEqual(translations[2]["translatedText"].lower(), u"ich heiße jeff") + self.assertEqual(translations[3]["detectedSourceLanguage"], "en") self.assertEqual( - translations[3]['detectedSourceLanguage'], 'en') - self.assertEqual( - translations[3]['translatedText'].lower(), 'mein name ist jeff') + translations[3]["translatedText"].lower(), "mein name ist jeff" + ) diff --git a/packages/google-cloud-translate/tests/unit/test__http.py b/packages/google-cloud-translate/tests/unit/test__http.py index ee93d7232dcd..714ace292c0b 100644 --- a/packages/google-cloud-translate/tests/unit/test__http.py +++ b/packages/google-cloud-translate/tests/unit/test__http.py @@ -18,7 +18,6 @@ class TestConnection(unittest.TestCase): - @staticmethod def _get_target_class(): from google.cloud.translate_v2._http import Connection @@ -30,27 +29,21 @@ def _make_one(self, *args, **kw): def test_build_api_url_no_extra_query_params(self): conn = self._make_one(object()) - URI = '/'.join([ - conn.API_BASE_URL, - 'language', - 'translate', - conn.API_VERSION, - 'foo', - ]) - self.assertEqual(conn.build_api_url('/foo'), URI) + URI = "/".join( + [conn.API_BASE_URL, "language", "translate", conn.API_VERSION, "foo"] + ) + self.assertEqual(conn.build_api_url("/foo"), URI) def test_build_api_url_w_extra_query_params(self): from six.moves.urllib.parse import parse_qsl from six.moves.urllib.parse import urlsplit conn = self._make_one(object()) - query_params = [('q', 'val1'), ('q', 'val2')] - uri = conn.build_api_url('/foo', query_params=query_params) + query_params = [("q", "val1"), ("q", "val2")] + uri = conn.build_api_url("/foo", query_params=query_params) scheme, netloc, path, qs, _ = urlsplit(uri) - self.assertEqual('%s://%s' % (scheme, netloc), - conn.API_BASE_URL) - expected_path = '/'.join( - ['', 'language', 'translate', conn.API_VERSION, 'foo']) + self.assertEqual("%s://%s" % (scheme, netloc), conn.API_BASE_URL) + expected_path = "/".join(["", "language", "translate", conn.API_VERSION, "foo"]) self.assertEqual(path, expected_path) params = parse_qsl(qs) self.assertEqual(params, query_params) @@ -64,26 +57,22 @@ def test_extra_headers(self): http = mock.create_autospec(requests.Session, instance=True) response = requests.Response() response.status_code = 200 - data = b'brent-spiner' + data = b"brent-spiner" response._content = data http.request.return_value = response - client = mock.Mock(_http=http, spec=['_http']) + client = mock.Mock(_http=http, spec=["_http"]) conn = self._make_one(client) - req_data = 'req-data-boring' - result = conn.api_request( - 'GET', '/rainbow', data=req_data, expect_json=False) + req_data = "req-data-boring" + result = conn.api_request("GET", "/rainbow", data=req_data, expect_json=False) self.assertEqual(result, data) expected_headers = { - 'Accept-Encoding': 'gzip', + "Accept-Encoding": "gzip", base_http.CLIENT_INFO_HEADER: MUT._CLIENT_INFO, - 'User-Agent': conn.USER_AGENT, + "User-Agent": conn.USER_AGENT, } - expected_uri = conn.build_api_url('/rainbow') + expected_uri = conn.build_api_url("/rainbow") http.request.assert_called_once_with( - data=req_data, - headers=expected_headers, - method='GET', - url=expected_uri, + data=req_data, headers=expected_headers, method="GET", url=expected_uri ) diff --git a/packages/google-cloud-translate/tests/unit/test_client.py b/packages/google-cloud-translate/tests/unit/test_client.py index 038f1484e696..1fe19451e39e 100644 --- a/packages/google-cloud-translate/tests/unit/test_client.py +++ b/packages/google-cloud-translate/tests/unit/test_client.py @@ -16,10 +16,10 @@ class TestClient(unittest.TestCase): - @staticmethod def _get_target_class(): from google.cloud.translate import Client + return Client def _make_one(self, *args, **kw): @@ -40,7 +40,7 @@ def test_constructor_non_default(self): from google.cloud.translate_v2._http import Connection http = object() - target = 'es' + target = "es" client = self._make_one(target_language=target, _http=http) self.assertIsInstance(client._connection, Connection) self.assertIsNone(client._connection.credentials) @@ -52,15 +52,11 @@ def test_get_languages(self): client = self._make_one(_http=object()) supported = [ - {'language': 'en', 'name': 'English'}, - {'language': 'af', 'name': 'Afrikaans'}, - {'language': 'am', 'name': 'Amharic'}, + {"language": "en", "name": "English"}, + {"language": "af", "name": "Afrikaans"}, + {"language": "am", "name": "Amharic"}, ] - data = { - 'data': { - 'languages': supported, - }, - } + data = {"data": {"languages": supported}} conn = client._connection = _Connection(data) result = client.get_languages() @@ -69,24 +65,14 @@ def test_get_languages(self): # Verify requested. self.assertEqual(len(conn._requested), 1) req = conn._requested[0] - self.assertEqual(req['method'], 'GET') - self.assertEqual(req['path'], '/languages') - self.assertEqual(req['query_params'], - {'target': ENGLISH_ISO_639}) + self.assertEqual(req["method"], "GET") + self.assertEqual(req["path"], "/languages") + self.assertEqual(req["query_params"], {"target": ENGLISH_ISO_639}) def test_get_languages_no_target(self): - client = self._make_one( - target_language=None, _http=object()) - supported = [ - {'language': 'en'}, - {'language': 'af'}, - {'language': 'am'}, - ] - data = { - 'data': { - 'languages': supported, - }, - } + client = self._make_one(target_language=None, _http=object()) + supported = [{"language": "en"}, {"language": "af"}, {"language": "am"}] + data = {"data": {"languages": supported}} conn = client._connection = _Connection(data) result = client.get_languages() @@ -96,23 +82,19 @@ def test_get_languages_no_target(self): self.assertEqual(len(conn._requested), 1) req = conn._requested[0] self.assertEqual(len(req), 3) - self.assertEqual(req['method'], 'GET') - self.assertEqual(req['path'], '/languages') - self.assertEqual(req['query_params'], {}) + self.assertEqual(req["method"], "GET") + self.assertEqual(req["path"], "/languages") + self.assertEqual(req["query_params"], {}) def test_get_languages_explicit_target(self): client = self._make_one(_http=object()) - target_language = 'en' + target_language = "en" supported = [ - {'language': 'en', 'name': 'Spanish'}, - {'language': 'af', 'name': 'Afrikaans'}, - {'language': 'am', 'name': 'Amharic'}, + {"language": "en", "name": "Spanish"}, + {"language": "af", "name": "Afrikaans"}, + {"language": "am", "name": "Amharic"}, ] - data = { - 'data': { - 'languages': supported, - }, - } + data = {"data": {"languages": supported}} conn = client._connection = _Connection(data) result = client.get_languages(target_language) @@ -121,14 +103,13 @@ def test_get_languages_explicit_target(self): # Verify requested. self.assertEqual(len(conn._requested), 1) req = conn._requested[0] - self.assertEqual(req['method'], 'GET') - self.assertEqual(req['path'], '/languages') - self.assertEqual(req['query_params'], - {'target': target_language}) + self.assertEqual(req["method"], "GET") + self.assertEqual(req["path"], "/languages") + self.assertEqual(req["query_params"], {"target": target_language}) def test_detect_language_bad_result(self): client = self._make_one(_http=object()) - value = 'takoy' + value = "takoy" conn = client._connection = _Connection({}) with self.assertRaises(ValueError): @@ -137,27 +118,21 @@ def test_detect_language_bad_result(self): # Verify requested. self.assertEqual(len(conn._requested), 1) req = conn._requested[0] - self.assertEqual(req['method'], 'POST') - self.assertEqual(req['path'], '/detect') - expected_data = { - 'q': [value], - } - self.assertEqual(req['data'], expected_data) + self.assertEqual(req["method"], "POST") + self.assertEqual(req["path"], "/detect") + expected_data = {"q": [value]} + self.assertEqual(req["data"], expected_data) def test_detect_language_single_value(self): client = self._make_one(_http=object()) - value = 'takoy' + value = "takoy" detection = { - 'confidence': 1.0, - 'input': value, - 'language': 'ru', - 'isReliable': False, - } - data = { - 'data': { - 'detections': [[detection]], - }, + "confidence": 1.0, + "input": value, + "language": "ru", + "isReliable": False, } + data = {"data": {"detections": [[detection]]}} conn = client._connection = _Connection(data) result = client.detect_language(value) @@ -166,37 +141,28 @@ def test_detect_language_single_value(self): # Verify requested. self.assertEqual(len(conn._requested), 1) req = conn._requested[0] - self.assertEqual(req['method'], 'POST') - self.assertEqual(req['path'], '/detect') - expected_data = { - 'q': [value], - } - self.assertEqual(req['data'], expected_data) + self.assertEqual(req["method"], "POST") + self.assertEqual(req["path"], "/detect") + expected_data = {"q": [value]} + self.assertEqual(req["data"], expected_data) def test_detect_language_multiple_values(self): client = self._make_one(_http=object()) - value1 = u'fa\xe7ade' # facade (with a cedilla) + value1 = u"fa\xe7ade" # facade (with a cedilla) detection1 = { - 'confidence': 0.6166008, - 'input': value1, - 'isReliable': False, - 'language': 'en', + "confidence": 0.6166008, + "input": value1, + "isReliable": False, + "language": "en", } - value2 = 's\'il vous plait' + value2 = "s'il vous plait" detection2 = { - 'confidence': 0.29728225, - 'input': value2, - 'isReliable': False, - 'language': 'fr', - } - data = { - 'data': { - 'detections': [ - [detection1], - [detection2], - ], - }, + "confidence": 0.29728225, + "input": value2, + "isReliable": False, + "language": "fr", } + data = {"data": {"detections": [[detection1], [detection2]]}} conn = client._connection = _Connection(data) result = client.detect_language([value1, value2]) @@ -205,33 +171,27 @@ def test_detect_language_multiple_values(self): # Verify requested. self.assertEqual(len(conn._requested), 1) req = conn._requested[0] - self.assertEqual(req['method'], 'POST') - self.assertEqual(req['path'], '/detect') - expected_data = { - 'q': [value1, value2], - } - self.assertEqual(req['data'], expected_data) + self.assertEqual(req["method"], "POST") + self.assertEqual(req["path"], "/detect") + expected_data = {"q": [value1, value2]} + self.assertEqual(req["data"], expected_data) def test_detect_language_multiple_results(self): client = self._make_one(_http=object()) - value = 'soy' + value = "soy" detection1 = { - 'confidence': 0.81496066, - 'input': value, - 'language': 'es', - 'isReliable': False, + "confidence": 0.81496066, + "input": value, + "language": "es", + "isReliable": False, } detection2 = { - 'confidence': 0.222, - 'input': value, - 'language': 'en', - 'isReliable': False, - } - data = { - 'data': { - 'detections': [[detection1, detection2]], - }, + "confidence": 0.222, + "input": value, + "language": "en", + "isReliable": False, } + data = {"data": {"detections": [[detection1, detection2]]}} client._connection = _Connection(data) with self.assertRaises(ValueError): @@ -239,7 +199,7 @@ def test_detect_language_multiple_results(self): def test_translate_bad_result(self): client = self._make_one(_http=object()) - value = 'hvala ti' + value = "hvala ti" conn = client._connection = _Connection({}) with self.assertRaises(ValueError): @@ -248,31 +208,27 @@ def test_translate_bad_result(self): # Verify requested. self.assertEqual(len(conn._requested), 1) req = conn._requested[0] - self.assertEqual(req['method'], 'POST') - self.assertEqual(req['path'], '') + self.assertEqual(req["method"], "POST") + self.assertEqual(req["path"], "") expected_data = { - 'target': 'en', - 'q': [value], - 'cid': (), - 'source': None, - 'model': None, - 'format': None, + "target": "en", + "q": [value], + "cid": (), + "source": None, + "model": None, + "format": None, } - self.assertEqual(req['data'], expected_data) + self.assertEqual(req["data"], expected_data) def test_translate_defaults(self): client = self._make_one(_http=object()) - value = 'hvala ti' + value = "hvala ti" translation = { - 'detectedSourceLanguage': 'hr', - 'translatedText': 'thank you', - 'input': value, - } - data = { - 'data': { - 'translations': [translation], - }, + "detectedSourceLanguage": "hr", + "translatedText": "thank you", + "input": value, } + data = {"data": {"translations": [translation]}} conn = client._connection = _Connection(data) result = client.translate(value) @@ -281,38 +237,34 @@ def test_translate_defaults(self): # Verify requested. self.assertEqual(len(conn._requested), 1) req = conn._requested[0] - self.assertEqual(req['method'], 'POST') - self.assertEqual(req['path'], '') + self.assertEqual(req["method"], "POST") + self.assertEqual(req["path"], "") expected_data = { - 'target': 'en', - 'q': [value], - 'cid': (), - 'source': None, - 'model': None, - 'format': None, + "target": "en", + "q": [value], + "cid": (), + "source": None, + "model": None, + "format": None, } - self.assertEqual(req['data'], expected_data) + self.assertEqual(req["data"], expected_data) def test_translate_multiple(self): client = self._make_one(_http=object()) - value1 = 'hvala ti' + value1 = "hvala ti" translation1 = { - 'detectedSourceLanguage': 'hr', - 'translatedText': 'thank you', - 'input': value1, + "detectedSourceLanguage": "hr", + "translatedText": "thank you", + "input": value1, } - value2 = 'Dankon' + value2 = "Dankon" translation2 = { - 'detectedSourceLanguage': 'eo', - 'translatedText': 'thank you', - 'input': value2, - } - data = { - 'data': { - 'translations': [translation1, translation2], - }, + "detectedSourceLanguage": "eo", + "translatedText": "thank you", + "input": value2, } + data = {"data": {"translations": [translation1, translation2]}} conn = client._connection = _Connection(data) result = client.translate([value1, value2]) @@ -321,63 +273,59 @@ def test_translate_multiple(self): # Verify requested. self.assertEqual(len(conn._requested), 1) req = conn._requested[0] - self.assertEqual(req['method'], 'POST') - self.assertEqual(req['path'], '') + self.assertEqual(req["method"], "POST") + self.assertEqual(req["path"], "") expected_data = { - 'target': 'en', - 'q': [value1, value2], - 'cid': (), - 'source': None, - 'model': None, - 'format': None, + "target": "en", + "q": [value1, value2], + "cid": (), + "source": None, + "model": None, + "format": None, } - self.assertEqual(req['data'], expected_data) + self.assertEqual(req["data"], expected_data) def test_translate_explicit(self): client = self._make_one(_http=object()) - value = 'thank you' - target_language = 'eo' - source_language = 'en' - translation = { - 'translatedText': 'Dankon', - 'input': value, - } - data = { - 'data': { - 'translations': [translation], - }, - } + value = "thank you" + target_language = "eo" + source_language = "en" + translation = {"translatedText": "Dankon", "input": value} + data = {"data": {"translations": [translation]}} conn = client._connection = _Connection(data) - cid = '123' - format_ = 'text' - model = 'nmt' - result = client.translate(value, target_language=target_language, - source_language=source_language, - format_=format_, customization_ids=cid, - model=model) + cid = "123" + format_ = "text" + model = "nmt" + result = client.translate( + value, + target_language=target_language, + source_language=source_language, + format_=format_, + customization_ids=cid, + model=model, + ) self.assertEqual(result, translation) # Verify requested. self.assertEqual(len(conn._requested), 1) req = conn._requested[0] - self.assertEqual(req['method'], 'POST') - self.assertEqual(req['path'], '') + self.assertEqual(req["method"], "POST") + self.assertEqual(req["path"], "") expected_data = { - 'target': target_language, - 'q': [value], - 'cid': [cid], - 'source': source_language, - 'model': model, - 'format': format_, + "target": target_language, + "q": [value], + "cid": [cid], + "source": source_language, + "model": model, + "format": format_, } - self.assertEqual(req['data'], expected_data) + self.assertEqual(req["data"], expected_data) class _Connection(object): - def __init__(self, *responses): self._responses = responses self._requested = []