From f51f05dc32011459f20c81621d06e4a7589ded91 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 9 Mar 2023 19:49:17 +0000 Subject: [PATCH 01/12] feat: added support for specifying waypoints as addresses docs: clarified usage of RouteLegStepTravelAdvisory in comment PiperOrigin-RevId: 515362180 Source-Link: https://github.com/googleapis/googleapis/commit/bb333b2e4758b9300dc2548c920d4ac4c34c9d59 Source-Link: https://github.com/googleapis/googleapis-gen/commit/969447f04c43260eab056106056baf3c041988f0 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcm91dGluZy8uT3dsQm90LnlhbWwiLCJoIjoiOTY5NDQ3ZjA0YzQzMjYwZWFiMDU2MTA2MDU2YmFmM2MwNDE5ODhmMCJ9 --- .../google-maps-routing/v2/.coveragerc | 13 + .../google-maps-routing/v2/.flake8 | 33 + .../google-maps-routing/v2/MANIFEST.in | 2 + .../google-maps-routing/v2/README.rst | 49 + .../google-maps-routing/v2/docs/conf.py | 376 ++++ .../google-maps-routing/v2/docs/index.rst | 7 + .../v2/docs/routing_v2/routes.rst | 6 + .../v2/docs/routing_v2/services.rst | 6 + .../v2/docs/routing_v2/types.rst | 6 + .../v2/google/maps/routing/__init__.py | 97 + .../v2/google/maps/routing/gapic_version.py | 16 + .../v2/google/maps/routing/py.typed | 2 + .../v2/google/maps/routing_v2/__init__.py | 98 + .../maps/routing_v2/gapic_metadata.json | 58 + .../google/maps/routing_v2/gapic_version.py | 16 + .../v2/google/maps/routing_v2/py.typed | 2 + .../maps/routing_v2/services/__init__.py | 15 + .../routing_v2/services/routes/__init__.py | 22 + .../services/routes/async_client.py | 416 ++++ .../maps/routing_v2/services/routes/client.py | 613 ++++++ .../services/routes/transports/__init__.py | 38 + .../services/routes/transports/base.py | 161 ++ .../services/routes/transports/grpc.py | 363 ++++ .../routes/transports/grpc_asyncio.py | 362 ++++ .../services/routes/transports/rest.py | 417 ++++ .../google/maps/routing_v2/types/__init__.py | 105 + .../maps/routing_v2/types/fallback_info.py | 103 + .../routing_v2/types/geocoding_results.py | 125 ++ .../google/maps/routing_v2/types/location.py | 62 + .../google/maps/routing_v2/types/maneuver.py | 96 + .../types/navigation_instruction.py | 58 + .../google/maps/routing_v2/types/polyline.py | 113 ++ .../v2/google/maps/routing_v2/types/route.py | 409 ++++ .../maps/routing_v2/types/route_label.py | 57 + .../maps/routing_v2/types/route_modifiers.py | 97 + .../routing_v2/types/route_travel_mode.py | 59 + .../maps/routing_v2/types/routes_service.py | 510 +++++ .../routing_v2/types/routing_preference.py | 67 + .../types/speed_reading_interval.py | 89 + .../google/maps/routing_v2/types/toll_info.py | 56 + .../maps/routing_v2/types/toll_passes.py | 348 ++++ .../v2/google/maps/routing_v2/types/units.py | 49 + .../routing_v2/types/vehicle_emission_type.py | 56 + .../maps/routing_v2/types/vehicle_info.py | 50 + .../google/maps/routing_v2/types/waypoint.py | 123 ++ .../google-maps-routing/v2/mypy.ini | 3 + .../google-maps-routing/v2/noxfile.py | 184 ++ ...rated_routes_compute_route_matrix_async.py | 52 + ...erated_routes_compute_route_matrix_sync.py | 52 + ...2_generated_routes_compute_routes_async.py | 51 + ...v2_generated_routes_compute_routes_sync.py | 51 + ...ippet_metadata_google.maps.routing.v2.json | 321 +++ .../v2/scripts/fixup_routing_v2_keywords.py | 177 ++ .../google-maps-routing/v2/setup.py | 90 + .../v2/testing/constraints-3.10.txt | 6 + .../v2/testing/constraints-3.11.txt | 6 + .../v2/testing/constraints-3.12.txt | 6 + .../v2/testing/constraints-3.7.txt | 9 + .../v2/testing/constraints-3.8.txt | 6 + .../v2/testing/constraints-3.9.txt | 6 + .../google-maps-routing/v2/tests/__init__.py | 16 + .../v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/routing_v2/__init__.py | 16 + .../unit/gapic/routing_v2/test_routes.py | 1750 +++++++++++++++++ 65 files changed, 8660 insertions(+) create mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc create mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 create mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py create mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini create mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json create mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py create mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py diff --git a/owl-bot-staging/google-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc new file mode 100644 index 000000000000..d0ce5597b0a9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/routing/__init__.py + google/maps/routing/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.flake8 @@ -0,0 +1,33 @@ +# -*- 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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in new file mode 100644 index 000000000000..c5b56c111c00 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/routing *.py +recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst new file mode 100644 index 000000000000..f0002366e552 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Routing API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Maps Routing API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py new file mode 100644 index 000000000000..d7a10abed96b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-maps-routing documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +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"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-maps-routing" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# 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"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# 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 + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +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 = { + "description": "Google Maps Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# 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 + +# 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 + +# 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, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# 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 = [] + +# 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' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is 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 = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# 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' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# 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' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-maps-routing-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- 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', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-maps-routing.tex", + u"google-maps-routing 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 + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# 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 = [ + ( + root_doc, + "google-maps-routing", + u"Google Maps Routing Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-maps-routing", + u"google-maps-routing Documentation", + author, + "google-maps-routing", + "GAPIC library for Google Maps Routing API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# 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), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst new file mode 100644 index 000000000000..e2563dd88ee9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + routing_v2/services + routing_v2/types diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst new file mode 100644 index 000000000000..3d52309cddae --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst @@ -0,0 +1,6 @@ +Routes +------------------------ + +.. automodule:: google.maps.routing_v2.services.routes + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst new file mode 100644 index 000000000000..e96568dc434c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst @@ -0,0 +1,6 @@ +Services for Google Maps Routing v2 API +======================================= +.. toctree:: + :maxdepth: 2 + + routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst new file mode 100644 index 000000000000..176a5a812cf8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst @@ -0,0 +1,6 @@ +Types for Google Maps Routing v2 API +==================================== + +.. automodule:: google.maps.routing_v2.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py new file mode 100644 index 000000000000..59020a3484c3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.maps.routing import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.routing_v2.services.routes.client import RoutesClient +from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient + +from google.maps.routing_v2.types.fallback_info import FallbackInfo +from google.maps.routing_v2.types.fallback_info import FallbackReason +from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode +from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint +from google.maps.routing_v2.types.geocoding_results import GeocodingResults +from google.maps.routing_v2.types.location import Location +from google.maps.routing_v2.types.maneuver import Maneuver +from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction +from google.maps.routing_v2.types.polyline import Polyline +from google.maps.routing_v2.types.polyline import PolylineEncoding +from google.maps.routing_v2.types.polyline import PolylineQuality +from google.maps.routing_v2.types.route import Route +from google.maps.routing_v2.types.route import RouteLeg +from google.maps.routing_v2.types.route import RouteLegStep +from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory +from google.maps.routing_v2.types.route import RouteLegTravelAdvisory +from google.maps.routing_v2.types.route import RouteTravelAdvisory +from google.maps.routing_v2.types.route_label import RouteLabel +from google.maps.routing_v2.types.route_modifiers import RouteModifiers +from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode +from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse +from google.maps.routing_v2.types.routes_service import RouteMatrixDestination +from google.maps.routing_v2.types.routes_service import RouteMatrixElement +from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin +from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition +from google.maps.routing_v2.types.routing_preference import RoutingPreference +from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval +from google.maps.routing_v2.types.toll_info import TollInfo +from google.maps.routing_v2.types.toll_passes import TollPass +from google.maps.routing_v2.types.units import Units +from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType +from google.maps.routing_v2.types.vehicle_info import VehicleInfo +from google.maps.routing_v2.types.waypoint import Waypoint + +__all__ = ('RoutesClient', + 'RoutesAsyncClient', + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py new file mode 100644 index 000000000000..405b1cebcf15 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py new file mode 100644 index 000000000000..cd9d694f63c6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.maps.routing_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.routes import RoutesClient +from .services.routes import RoutesAsyncClient + +from .types.fallback_info import FallbackInfo +from .types.fallback_info import FallbackReason +from .types.fallback_info import FallbackRoutingMode +from .types.geocoding_results import GeocodedWaypoint +from .types.geocoding_results import GeocodingResults +from .types.location import Location +from .types.maneuver import Maneuver +from .types.navigation_instruction import NavigationInstruction +from .types.polyline import Polyline +from .types.polyline import PolylineEncoding +from .types.polyline import PolylineQuality +from .types.route import Route +from .types.route import RouteLeg +from .types.route import RouteLegStep +from .types.route import RouteLegStepTravelAdvisory +from .types.route import RouteLegTravelAdvisory +from .types.route import RouteTravelAdvisory +from .types.route_label import RouteLabel +from .types.route_modifiers import RouteModifiers +from .types.route_travel_mode import RouteTravelMode +from .types.routes_service import ComputeRouteMatrixRequest +from .types.routes_service import ComputeRoutesRequest +from .types.routes_service import ComputeRoutesResponse +from .types.routes_service import RouteMatrixDestination +from .types.routes_service import RouteMatrixElement +from .types.routes_service import RouteMatrixOrigin +from .types.routes_service import RouteMatrixElementCondition +from .types.routing_preference import RoutingPreference +from .types.speed_reading_interval import SpeedReadingInterval +from .types.toll_info import TollInfo +from .types.toll_passes import TollPass +from .types.units import Units +from .types.vehicle_emission_type import VehicleEmissionType +from .types.vehicle_info import VehicleInfo +from .types.waypoint import Waypoint + +__all__ = ( + 'RoutesAsyncClient', +'ComputeRouteMatrixRequest', +'ComputeRoutesRequest', +'ComputeRoutesResponse', +'FallbackInfo', +'FallbackReason', +'FallbackRoutingMode', +'GeocodedWaypoint', +'GeocodingResults', +'Location', +'Maneuver', +'NavigationInstruction', +'Polyline', +'PolylineEncoding', +'PolylineQuality', +'Route', +'RouteLabel', +'RouteLeg', +'RouteLegStep', +'RouteLegStepTravelAdvisory', +'RouteLegTravelAdvisory', +'RouteMatrixDestination', +'RouteMatrixElement', +'RouteMatrixElementCondition', +'RouteMatrixOrigin', +'RouteModifiers', +'RouteTravelAdvisory', +'RouteTravelMode', +'RoutesClient', +'RoutingPreference', +'SpeedReadingInterval', +'TollInfo', +'TollPass', +'Units', +'VehicleEmissionType', +'VehicleInfo', +'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json new file mode 100644 index 000000000000..8382cea1d39a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json @@ -0,0 +1,58 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.routing_v2", + "protoPackage": "google.maps.routing.v2", + "schema": "1.0", + "services": { + "Routes": { + "clients": { + "grpc": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RoutesAsyncClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "rest": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py new file mode 100644 index 000000000000..405b1cebcf15 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py new file mode 100644 index 000000000000..e8e1c3845db5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py new file mode 100644 index 000000000000..ff3f8f71863f --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RoutesClient +from .async_client import RoutesAsyncClient + +__all__ = ( + 'RoutesClient', + 'RoutesAsyncClient', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py new file mode 100644 index 000000000000..7f8df74a140b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union + +from google.maps.routing_v2 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .client import RoutesClient + + +class RoutesAsyncClient: + """The Routes API.""" + + _client: RoutesClient + + DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RoutesClient.common_folder_path) + parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) + common_organization_path = staticmethod(RoutesClient.common_organization_path) + parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) + common_project_path = staticmethod(RoutesClient.common_project_path) + parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) + common_location_path = staticmethod(RoutesClient.common_location_path) + parse_common_location_path = staticmethod(RoutesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(RoutesClient).get_transport_class, type(RoutesClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RoutesTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RoutesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RoutesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # Create or coerce a protobuf request object. + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compute_routes, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + # Create or coerce a protobuf request object. + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compute_route_matrix, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RoutesAsyncClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py new file mode 100644 index 000000000000..1943383c7246 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py @@ -0,0 +1,613 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast + +from google.maps.routing_v2 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RoutesGrpcTransport +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .transports.rest import RoutesRestTransport + + +class RoutesClientMeta(type): + """Metaclass for the Routes client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] + _transport_registry["grpc"] = RoutesGrpcTransport + _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport + _transport_registry["rest"] = RoutesRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RoutesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RoutesClient(metaclass=RoutesClientMeta): + """The Routes API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "routes.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RoutesTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, RoutesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RoutesTransport): + # transport is a RoutesTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a routes_service.ComputeRoutesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, routes_service.ComputeRoutesRequest): + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_routes] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[routes_service.RouteMatrixElement]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.maps.routing_v2.types.RouteMatrixElement]: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a routes_service.ComputeRouteMatrixRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, routes_service.ComputeRouteMatrixRequest): + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RoutesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RoutesClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py new file mode 100644 index 000000000000..a15967f001c9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RoutesTransport +from .grpc import RoutesGrpcTransport +from .grpc_asyncio import RoutesGrpcAsyncIOTransport +from .rest import RoutesRestTransport +from .rest import RoutesRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] +_transport_registry['grpc'] = RoutesGrpcTransport +_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport +_transport_registry['rest'] = RoutesRestTransport + +__all__ = ( + 'RoutesTransport', + 'RoutesGrpcTransport', + 'RoutesGrpcAsyncIOTransport', + 'RoutesRestTransport', + 'RoutesRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py new file mode 100644 index 000000000000..a6fa68993eca --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.maps.routing_v2 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.maps.routing_v2.types import routes_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class RoutesTransport(abc.ABC): + """Abstract transport class for Routes.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'routes.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.compute_routes: gapic_v1.method.wrap_method( + self.compute_routes, + default_timeout=None, + client_info=client_info, + ), + self.compute_route_matrix: gapic_v1.method.wrap_method( + self.compute_route_matrix, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Union[ + routes_service.ComputeRoutesResponse, + Awaitable[routes_service.ComputeRoutesResponse] + ]]: + raise NotImplementedError() + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Union[ + routes_service.RouteMatrixElement, + Awaitable[routes_service.RouteMatrixElement] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RoutesTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py new file mode 100644 index 000000000000..8316c8b03587 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py @@ -0,0 +1,363 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO + + +class RoutesGrpcTransport(RoutesTransport): + """gRPC backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + ~.ComputeRoutesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self.grpc_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + ~.RouteMatrixElement]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RoutesGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py new file mode 100644 index 000000000000..752c5eaefc33 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO +from .grpc import RoutesGrpcTransport + + +class RoutesGrpcAsyncIOTransport(RoutesTransport): + """gRPC AsyncIO backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Awaitable[routes_service.ComputeRoutesResponse]]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + Awaitable[~.ComputeRoutesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self.grpc_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Awaitable[routes_service.RouteMatrixElement]]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + Awaitable[~.RouteMatrixElement]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'RoutesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py new file mode 100644 index 000000000000..c7fdf524b0c7 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.maps.routing_v2.types import routes_service + +from .base import RoutesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RoutesRestInterceptor: + """Interceptor for Routes. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RoutesRestTransport. + + .. code-block:: python + class MyCustomRoutesInterceptor(RoutesRestInterceptor): + def pre_compute_route_matrix(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_route_matrix(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_compute_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_routes(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) + client = RoutesClient(transport=transport) + + + """ + def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: + """Post-rpc interceptor for compute_routes + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RoutesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RoutesRestInterceptor + + +class RoutesRestTransport(RoutesTransport): + """REST backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[RoutesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RoutesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ComputeRouteMatrix(RoutesRestStub): + def __hash__(self): + return hash("ComputeRouteMatrix") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: routes_service.ComputeRouteMatrixRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + r"""Call the compute route matrix method over HTTP. + + Args: + request (~.routes_service.ComputeRouteMatrixRequest): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.routes_service.RouteMatrixElement: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/distanceMatrix/v2:computeRouteMatrix', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) + pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) + resp = self._interceptor.post_compute_route_matrix(resp) + return resp + + class _ComputeRoutes(RoutesRestStub): + def __hash__(self): + return hash("ComputeRoutes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: routes_service.ComputeRoutesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> routes_service.ComputeRoutesResponse: + r"""Call the compute routes method over HTTP. + + Args: + request (~.routes_service.ComputeRoutesRequest): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.routes_service.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/directions/v2:computeRoutes', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_compute_routes(request, metadata) + pb_request = routes_service.ComputeRoutesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = routes_service.ComputeRoutesResponse() + pb_resp = routes_service.ComputeRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_compute_routes(resp) + return resp + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RoutesRestTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py new file mode 100644 index 000000000000..7323899cfc30 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .fallback_info import ( + FallbackInfo, + FallbackReason, + FallbackRoutingMode, +) +from .geocoding_results import ( + GeocodedWaypoint, + GeocodingResults, +) +from .location import ( + Location, +) +from .navigation_instruction import ( + NavigationInstruction, +) +from .polyline import ( + Polyline, + PolylineEncoding, + PolylineQuality, +) +from .route import ( + Route, + RouteLeg, + RouteLegStep, + RouteLegStepTravelAdvisory, + RouteLegTravelAdvisory, + RouteTravelAdvisory, +) +from .route_modifiers import ( + RouteModifiers, +) +from .routes_service import ( + ComputeRouteMatrixRequest, + ComputeRoutesRequest, + ComputeRoutesResponse, + RouteMatrixDestination, + RouteMatrixElement, + RouteMatrixOrigin, + RouteMatrixElementCondition, +) +from .speed_reading_interval import ( + SpeedReadingInterval, +) +from .toll_info import ( + TollInfo, +) +from .vehicle_info import ( + VehicleInfo, +) +from .waypoint import ( + Waypoint, +) + +__all__ = ( + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py new file mode 100644 index 000000000000..99670aafac25 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'FallbackReason', + 'FallbackRoutingMode', + 'FallbackInfo', + }, +) + + +class FallbackReason(proto.Enum): + r"""Reasons for using fallback response. + + Values: + FALLBACK_REASON_UNSPECIFIED (0): + No fallback reason specified. + SERVER_ERROR (1): + A server error happened while calculating + routes with your preferred routing mode, but we + were able to return a result calculated by an + alternative mode. + LATENCY_EXCEEDED (2): + We were not able to finish the calculation + with your preferred routing mode on time, but we + were able to return a result calculated by an + alternative mode. + """ + FALLBACK_REASON_UNSPECIFIED = 0 + SERVER_ERROR = 1 + LATENCY_EXCEEDED = 2 + + +class FallbackRoutingMode(proto.Enum): + r"""Actual routing mode used for returned fallback response. + + Values: + FALLBACK_ROUTING_MODE_UNSPECIFIED (0): + Not used. + FALLBACK_TRAFFIC_UNAWARE (1): + Indicates the "TRAFFIC_UNAWARE" routing mode was used to + compute the response. + FALLBACK_TRAFFIC_AWARE (2): + Indicates the "TRAFFIC_AWARE" routing mode was used to + compute the response. + """ + FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 + FALLBACK_TRAFFIC_UNAWARE = 1 + FALLBACK_TRAFFIC_AWARE = 2 + + +class FallbackInfo(proto.Message): + r"""Information related to how and why a fallback result was + used. If this field is set, then it means the server used a + different routing mode from your preferred mode as fallback. + + Attributes: + routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): + Routing mode used for the response. If + fallback was triggered, the mode may be + different from routing preference set in the + original client request. + reason (google.maps.routing_v2.types.FallbackReason): + The reason why fallback response was used + instead of the original response. This field is + only populated when the fallback mode is + triggered and the fallback response is returned. + """ + + routing_mode: 'FallbackRoutingMode' = proto.Field( + proto.ENUM, + number=1, + enum='FallbackRoutingMode', + ) + reason: 'FallbackReason' = proto.Field( + proto.ENUM, + number=2, + enum='FallbackReason', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py new file mode 100644 index 000000000000..ffa385a59a75 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'GeocodingResults', + 'GeocodedWaypoint', + }, +) + + +class GeocodingResults(proto.Message): + r"""Contains GeocodedWaypoints for origin, destination and + intermediate waypoints. Only populated for address waypoints. + + Attributes: + origin (google.maps.routing_v2.types.GeocodedWaypoint): + Origin geocoded waypoint. + destination (google.maps.routing_v2.types.GeocodedWaypoint): + Destination geocoded waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.GeocodedWaypoint]): + A list of intermediate geocoded waypoints + each containing an index field that corresponds + to the zero-based position of the waypoint in + the order they were specified in the request. + """ + + origin: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=1, + message='GeocodedWaypoint', + ) + destination: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=2, + message='GeocodedWaypoint', + ) + intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='GeocodedWaypoint', + ) + + +class GeocodedWaypoint(proto.Message): + r"""Details about the locations used as waypoints. Only populated + for address waypoints. Includes details about the geocoding + results for the purposes of determining what the address was + geocoded to. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + geocoder_status (google.rpc.status_pb2.Status): + Indicates the status code resulting from the + geocoding operation. + intermediate_waypoint_request_index (int): + The index of the corresponding intermediate + waypoint in the request. Only populated if the + corresponding waypoint is an intermediate + waypoint. + + This field is a member of `oneof`_ ``_intermediate_waypoint_request_index``. + type_ (MutableSequence[str]): + The type(s) of the result, in the form of + zero or more type tags. Supported types: + https://developers.google.com/maps/documentation/geocoding/requests-geocoding#Types + partial_match (bool): + Indicates that the geocoder did not return an + exact match for the original request, though it + was able to match part of the requested address. + You may wish to examine the original request for + misspellings and/or an incomplete address. + place_id (str): + The place ID for this result. + """ + + geocoder_status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + intermediate_waypoint_request_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + type_: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + partial_match: bool = proto.Field( + proto.BOOL, + number=4, + ) + place_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py new file mode 100644 index 000000000000..722cd7dda46a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Location', + }, +) + + +class Location(proto.Message): + r"""Encapsulates a location (a geographic point, and an optional + heading). + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + The waypoint's geographic coordinates. + heading (google.protobuf.wrappers_pb2.Int32Value): + The compass heading associated with the direction of the + flow of traffic. This value is used to specify the side of + the road to use for pickup and drop-off. Heading values can + be from 0 to 360, where 0 specifies a heading of due North, + 90 specifies a heading of due East, etc. You can use this + field only for ``DRIVE`` and ``TWO_WHEELER`` travel modes. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + heading: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py new file mode 100644 index 000000000000..60e5cd3cb9c6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Maneuver', + }, +) + + +class Maneuver(proto.Enum): + r"""A set of values that specify the navigation action to take + for the current step (e.g., turn left, merge, straight, etc.). + + Values: + MANEUVER_UNSPECIFIED (0): + Not used. + TURN_SLIGHT_LEFT (1): + Turn slightly to the left. + TURN_SHARP_LEFT (2): + Turn sharply to the left. + UTURN_LEFT (3): + Make a left u-turn. + TURN_LEFT (4): + Turn left. + TURN_SLIGHT_RIGHT (5): + Turn slightly to the right. + TURN_SHARP_RIGHT (6): + Turn sharply to the right. + UTURN_RIGHT (7): + Make a right u-turn. + TURN_RIGHT (8): + Turn right. + STRAIGHT (9): + Go straight. + RAMP_LEFT (10): + Take the left ramp. + RAMP_RIGHT (11): + Take the right ramp. + MERGE (12): + Merge into traffic. + FORK_LEFT (13): + Take the left fork. + FORK_RIGHT (14): + Take the right fork. + FERRY (15): + Take the ferry. + FERRY_TRAIN (16): + Take the train leading onto the ferry. + ROUNDABOUT_LEFT (17): + Turn left at the roundabout. + ROUNDABOUT_RIGHT (18): + Turn right at the roundabout. + """ + MANEUVER_UNSPECIFIED = 0 + TURN_SLIGHT_LEFT = 1 + TURN_SHARP_LEFT = 2 + UTURN_LEFT = 3 + TURN_LEFT = 4 + TURN_SLIGHT_RIGHT = 5 + TURN_SHARP_RIGHT = 6 + UTURN_RIGHT = 7 + TURN_RIGHT = 8 + STRAIGHT = 9 + RAMP_LEFT = 10 + RAMP_RIGHT = 11 + MERGE = 12 + FORK_LEFT = 13 + FORK_RIGHT = 14 + FERRY = 15 + FERRY_TRAIN = 16 + ROUNDABOUT_LEFT = 17 + ROUNDABOUT_RIGHT = 18 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py new file mode 100644 index 000000000000..dc8b69e76ccd --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import maneuver as gmr_maneuver + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'NavigationInstruction', + }, +) + + +class NavigationInstruction(proto.Message): + r"""Encapsulates navigation instructions for a + [RouteLegStep][google.maps.routing.v2.RouteLegStep] + + Attributes: + maneuver (google.maps.routing_v2.types.Maneuver): + Encapsulates the navigation instructions for + the current step (e.g., turn left, merge, + straight, etc.). This field determines which + icon to display. + instructions (str): + Instructions for navigating this step. + """ + + maneuver: gmr_maneuver.Maneuver = proto.Field( + proto.ENUM, + number=1, + enum=gmr_maneuver.Maneuver, + ) + instructions: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py new file mode 100644 index 000000000000..4d9630691288 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'PolylineQuality', + 'PolylineEncoding', + 'Polyline', + }, +) + + +class PolylineQuality(proto.Enum): + r"""A set of values that specify the quality of the polyline. + + Values: + POLYLINE_QUALITY_UNSPECIFIED (0): + No polyline quality preference specified. Defaults to + ``OVERVIEW``. + HIGH_QUALITY (1): + Specifies a high-quality polyline - which is composed using + more points than ``OVERVIEW``, at the cost of increased + response size. Use this value when you need more precision. + OVERVIEW (2): + Specifies an overview polyline - which is composed using a + small number of points. Use this value when displaying an + overview of the route. Using this option has a lower request + latency compared to using the ``HIGH_QUALITY`` option. + """ + POLYLINE_QUALITY_UNSPECIFIED = 0 + HIGH_QUALITY = 1 + OVERVIEW = 2 + + +class PolylineEncoding(proto.Enum): + r"""Specifies the preferred type of polyline to be returned. + + Values: + POLYLINE_ENCODING_UNSPECIFIED (0): + No polyline type preference specified. Defaults to + ``ENCODED_POLYLINE``. + ENCODED_POLYLINE (1): + Specifies a polyline encoded using the `polyline encoding + algorithm `__. + GEO_JSON_LINESTRING (2): + Specifies a polyline using the `GeoJSON LineString + format `__ + """ + POLYLINE_ENCODING_UNSPECIFIED = 0 + ENCODED_POLYLINE = 1 + GEO_JSON_LINESTRING = 2 + + +class Polyline(proto.Message): + r"""Encapsulates an encoded polyline. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + encoded_polyline (str): + The string encoding of the polyline using the `polyline + encoding + algorithm `__ + + This field is a member of `oneof`_ ``polyline_type``. + geo_json_linestring (google.protobuf.struct_pb2.Struct): + Specifies a polyline using the `GeoJSON LineString + format `__ + + This field is a member of `oneof`_ ``polyline_type``. + """ + + encoded_polyline: str = proto.Field( + proto.STRING, + number=1, + oneof='polyline_type', + ) + geo_json_linestring: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + oneof='polyline_type', + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py new file mode 100644 index 000000000000..2a57054febff --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py @@ -0,0 +1,409 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.geo.type import viewport_pb2 # type: ignore +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction +from google.maps.routing_v2.types import polyline as gmr_polyline +from google.maps.routing_v2.types import route_label +from google.maps.routing_v2.types import speed_reading_interval +from google.maps.routing_v2.types import toll_info as gmr_toll_info +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Route', + 'RouteTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteLegStepTravelAdvisory', + 'RouteLeg', + 'RouteLegStep', + }, +) + + +class Route(proto.Message): + r"""Encapsulates a route, which consists of a series of connected + road segments that join beginning, ending, and intermediate + waypoints. + + Attributes: + route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): + Labels for the ``Route`` that are useful to identify + specific properties of the route to compare against others. + legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): + A collection of legs (path segments between waypoints) that + make-up the route. Each leg corresponds to the trip between + two non-\ ``via`` Waypoints. For example, a route with no + intermediate waypoints has only one leg. A route that + includes one non-\ ``via`` intermediate waypoint has two + legs. A route that includes one ``via`` intermediate + waypoint has one leg. The order of the legs matches the + order of Waypoints from ``origin`` to ``intermediates`` to + ``destination``. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this + value is the same as ``static_duration``. If you set the + ``routing_preference`` to either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the route + without taking traffic conditions into + consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall route polyline. This polyline will be the + combined polyline of all ``legs``. + description (str): + A description of the route. + warnings (MutableSequence[str]): + An array of warnings to show when displaying + the route. + viewport (google.geo.type.viewport_pb2.Viewport): + The viewport bounding box of the polyline. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. + route_token (str): + Web-safe base64 encoded route token that can be passed to + NavigationSDK, which allows the Navigation SDK to + reconstruct the route during navigation, and in the event of + rerouting honor the original intention when Routes + ComputeRoutes is called. Customers should treat this token + as an opaque blob. NOTE: ``Route.route_token`` is only + available for requests that have set + ``ComputeRoutesRequest.routing_preference`` to + ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. + ``Route.route_token`` is also not supported for requests + that have Via waypoints. + """ + + route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( + proto.ENUM, + number=13, + enum=route_label.RouteLabel, + ) + legs: MutableSequence['RouteLeg'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteLeg', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=2, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_polyline.Polyline, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + warnings: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + viewport: viewport_pb2.Viewport = proto.Field( + proto.MESSAGE, + number=8, + message=viewport_pb2.Viewport, + ) + travel_advisory: 'RouteTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=9, + message='RouteTravelAdvisory', + ) + route_token: str = proto.Field( + proto.STRING, + number=12, + ) + + +class RouteTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction + etc. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Encapsulates information about tolls on the Route. This + field is only populated if we expect there are tolls on the + Route. If this field is set but the estimated_price subfield + is not populated, we expect that road contains tolls but we + do not know an estimated price. If this field is not set, + then we expect there is no toll on the Route. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the route without overlap. The + start point of a specified interval is the same as the end + point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + fuel_consumption_microliters (int): + The fuel consumption prediction in + microliters. + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=speed_reading_interval.SpeedReadingInterval, + ) + fuel_consumption_microliters: int = proto.Field( + proto.INT64, + number=5, + ) + + +class RouteLegTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction + etc. on a route leg. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Encapsulates information about tolls on the specific + RouteLeg. This field is only populated if we expect there + are tolls on the RouteLeg. If this field is set but the + estimated_price subfield is not populated, we expect that + road contains tolls but we do not know an estimated price. + If this field does not exist, then there is no toll on the + RouteLeg. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the RouteLg without overlap. + The start point of a specified interval is the same as the + end point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLegStepTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction on + a leg step. + + Attributes: + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + NOTE: This field is not currently populated. + """ + + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLeg(proto.Message): + r"""Encapsulates a segment between non-\ ``via`` waypoints. + + Attributes: + distance_meters (int): + The travel distance of the route leg, in + meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the leg. If the + ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then + this value is the same as ``static_duration``. If the + ``route_preference`` is either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the leg, + calculated without taking traffic conditions + into consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall polyline for this leg. This includes that each + ``step``'s polyline. + start_location (google.maps.routing_v2.types.Location): + The start location of this leg. This might be different from + the provided ``origin``. For example, when the provided + ``origin`` is not near a road, this is a point on the road. + end_location (google.maps.routing_v2.types.Location): + The end location of this leg. This might be different from + the provided ``destination``. For example, when the provided + ``destination`` is not near a road, this is a point on the + road. + steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): + An array of steps denoting segments within + this leg. Each step represents one navigation + instruction. + travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): + Encapsulates the additional information that + the user should be informed about, such as + possible traffic zone restriction etc. on a + route leg. + """ + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=4, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=6, + message=location.Location, + ) + steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='RouteLegStep', + ) + travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=8, + message='RouteLegTravelAdvisory', + ) + + +class RouteLegStep(proto.Message): + r"""Encapsulates a segment of a ``RouteLeg``. A step corresponds to a + single navigation instruction. Route legs are made up of steps. + + Attributes: + distance_meters (int): + The travel distance of this step, in meters. + In some circumstances, this field might not have + a value. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of travel through this step + without taking traffic conditions into + consideration. In some circumstances, this field + might not have a value. + polyline (google.maps.routing_v2.types.Polyline): + The polyline associated with this step. + start_location (google.maps.routing_v2.types.Location): + The start location of this step. + end_location (google.maps.routing_v2.types.Location): + The end location of this step. + navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): + Navigation instructions. + travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): + Encapsulates the additional information that + the user should be informed about, such as + possible traffic zone restriction on a leg step. + """ + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=4, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( + proto.MESSAGE, + number=6, + message=gmr_navigation_instruction.NavigationInstruction, + ) + travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=7, + message='RouteLegStepTravelAdvisory', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py new file mode 100644 index 000000000000..a3e095209d58 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteLabel', + }, +) + + +class RouteLabel(proto.Enum): + r"""Labels for the ``Route`` that are useful to identify specific + properties of the route to compare against others. + + Values: + ROUTE_LABEL_UNSPECIFIED (0): + Default - not used. + DEFAULT_ROUTE (1): + The default "best" route returned for the + route computation. + DEFAULT_ROUTE_ALTERNATE (2): + An alternative to the default "best" route. Routes like this + will be returned when + ``ComputeRoutesRequest.compute_alternative_routes`` is + specified. + FUEL_EFFICIENT (3): + Fuel efficient route. Routes labeled with + this value are determined to be optimized for + Eco parameters such as fuel consumption. + """ + ROUTE_LABEL_UNSPECIFIED = 0 + DEFAULT_ROUTE = 1 + DEFAULT_ROUTE_ALTERNATE = 2 + FUEL_EFFICIENT = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py new file mode 100644 index 000000000000..59f5e6420c4c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import toll_passes as gmr_toll_passes +from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteModifiers', + }, +) + + +class RouteModifiers(proto.Message): + r"""Encapsulates a set of optional conditions to satisfy when + calculating the routes. + + Attributes: + avoid_tolls (bool): + Specifies whether to avoid toll roads where reasonable. + Preference will be given to routes not containing toll + roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` + travel modes. + avoid_highways (bool): + Specifies whether to avoid highways where reasonable. + Preference will be given to routes not containing highways. + Applies only to the ``DRIVE`` and ``TWO_WHEELER`` travel + modes. + avoid_ferries (bool): + Specifies whether to avoid ferries where reasonable. + Preference will be given to routes not containing travel by + ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` + travel modes. + avoid_indoor (bool): + Specifies whether to avoid navigating indoors where + reasonable. Preference will be given to routes not + containing indoor navigation. Applies only to the ``WALK`` + travel mode. + vehicle_info (google.maps.routing_v2.types.VehicleInfo): + Specifies the vehicle information. + toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): + Encapsulates information about toll passes. If toll passes + are provided, the API tries to return the pass price. If + toll passes are not provided, the API treats the toll pass + as unknown and tries to return the cash price. Applies only + to the DRIVE and TWO_WHEELER travel modes. + """ + + avoid_tolls: bool = proto.Field( + proto.BOOL, + number=1, + ) + avoid_highways: bool = proto.Field( + proto.BOOL, + number=2, + ) + avoid_ferries: bool = proto.Field( + proto.BOOL, + number=3, + ) + avoid_indoor: bool = proto.Field( + proto.BOOL, + number=4, + ) + vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_vehicle_info.VehicleInfo, + ) + toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( + proto.ENUM, + number=6, + enum=gmr_toll_passes.TollPass, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py new file mode 100644 index 000000000000..14d466006fae --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteTravelMode', + }, +) + + +class RouteTravelMode(proto.Enum): + r"""A set of values used to specify the mode of travel. NOTE: WALK, + BICYCLE, and TWO_WHEELER routes are in beta and might sometimes be + missing clear sidewalks, pedestrian paths, or bicycling paths. You + must display this warning to the user for all walking, bicycling, + and two-wheel routes that you display in your app. + + Values: + TRAVEL_MODE_UNSPECIFIED (0): + No travel mode specified. Defaults to ``DRIVE``. + DRIVE (1): + Travel by passenger car. + BICYCLE (2): + Travel by bicycle. + WALK (3): + Travel by walking. + TWO_WHEELER (4): + Two-wheeled, motorized vehicle. For example, motorcycle. + Note that this differs from the ``BICYCLE`` travel mode + which covers human-powered mode. + """ + TRAVEL_MODE_UNSPECIFIED = 0 + DRIVE = 1 + BICYCLE = 2 + WALK = 3 + TWO_WHEELER = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py new file mode 100644 index 000000000000..12bb47231932 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py @@ -0,0 +1,510 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import fallback_info as gmr_fallback_info +from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routing_preference as gmr_routing_preference +from google.maps.routing_v2.types import units as gmr_units +from google.maps.routing_v2.types import waypoint as gmr_waypoint +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteMatrixElementCondition', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'ComputeRouteMatrixRequest', + 'RouteMatrixOrigin', + 'RouteMatrixDestination', + 'RouteMatrixElement', + }, +) + + +class RouteMatrixElementCondition(proto.Enum): + r"""The condition of the route being returned. + + Values: + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): + Only used when the ``status`` of the element is not OK. + ROUTE_EXISTS (1): + A route was found, and the corresponding + information was filled out for the element. + ROUTE_NOT_FOUND (2): + No route could be found. Fields containing route + information, such as ``distance_meters`` or ``duration``, + will not be filled out in the element. + """ + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 + ROUTE_EXISTS = 1 + ROUTE_NOT_FOUND = 2 + + +class ComputeRoutesRequest(proto.Message): + r"""ComputeRoutes request message. + + Attributes: + origin (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint. + destination (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): + Optional. A set of waypoints along the route + (excluding terminal points), for either stopping + at or passing by. Up to 25 intermediate + waypoints are supported. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, then an error is returned. You can + specify this option only when the ``travel_mode`` is + ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. + polyline_quality (google.maps.routing_v2.types.PolylineQuality): + Optional. Specifies your preference for the + quality of the polyline. + polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): + Optional. Specifies the preferred encoding + for the polyline. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't + set this value, then this value defaults to the + time that you made the request. If you set this + value to a time that has already occurred, then + the request fails. + compute_alternative_routes (bool): + Optional. Specifies whether to calculate + alternate routes in addition to the route. + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. A set of conditions to satisfy that + affect the way routes are calculated. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + See `Language + Support `__ + for the list of supported languages. When you don't provide + this value, the display language is inferred from the + location of the route request. + units (google.maps.routing_v2.types.Units): + Optional. Specifies the units of measure for the display + fields. This includes the ``instruction`` field in + ``NavigationInstruction``. The units of measure used for the + route, leg, step distance, and duration are not affected by + this value. If you don't provide this value, then the + display units are inferred from the location of the request. + requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): + Optional. Specifies what reference routes to calculate as + part of the request in addition to the default route. A + reference route is a route with a different route + calculation objective than the default route. For example an + FUEL_EFFICIENT reference route calculation takes into + account various parameters that would generate an optimal + fuel efficient route. + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + """ + class ReferenceRoute(proto.Enum): + r"""A supported reference route on the ComputeRoutesRequest. + + Values: + REFERENCE_ROUTE_UNSPECIFIED (0): + Not used. Requests containing this value + fail. + FUEL_EFFICIENT (1): + Fuel efficient route. Routes labeled with + this value are determined to be optimized for + parameters such as fuel consumption. + """ + REFERENCE_ROUTE_UNSPECIFIED = 0 + FUEL_EFFICIENT = 1 + + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the route(s). + FUEL_CONSUMPTION (2): + Estimated fuel consumption for the route(s). + TRAFFIC_ON_POLYLINE (3): + Traffic aware polylines for the route(s). + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + FUEL_CONSUMPTION = 2 + TRAFFIC_ON_POLYLINE = 3 + + origin: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + destination: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_waypoint.Waypoint, + ) + intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=gmr_waypoint.Waypoint, + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=4, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=5, + enum=gmr_routing_preference.RoutingPreference, + ) + polyline_quality: polyline.PolylineQuality = proto.Field( + proto.ENUM, + number=6, + enum=polyline.PolylineQuality, + ) + polyline_encoding: polyline.PolylineEncoding = proto.Field( + proto.ENUM, + number=12, + enum=polyline.PolylineEncoding, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + compute_alternative_routes: bool = proto.Field( + proto.BOOL, + number=8, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=9, + message=gmr_route_modifiers.RouteModifiers, + ) + language_code: str = proto.Field( + proto.STRING, + number=10, + ) + units: gmr_units.Units = proto.Field( + proto.ENUM, + number=11, + enum=gmr_units.Units, + ) + requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( + proto.ENUM, + number=14, + enum=ReferenceRoute, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=15, + enum=ExtraComputation, + ) + + +class ComputeRoutesResponse(proto.Message): + r"""ComputeRoutes the response message. + + Attributes: + routes (MutableSequence[google.maps.routing_v2.types.Route]): + Contains an array of computed routes (up to three) when you + specify compute_alternatives_routes, and contains just one + route when you don't. When this array contains multiple + entries, the first one is the most recommended route. If the + array is empty, then it means no route could be found. + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route results with all of the input + preferences, it may fallback to using a + different way of computation. When fallback mode + is used, this field contains detailed info about + the fallback response. Otherwise this field is + unset. + geocoding_results (google.maps.routing_v2.types.GeocodingResults): + Contains geocoding response info for + waypoints specified as addresses. + """ + + routes: MutableSequence[route.Route] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=route.Route, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_fallback_info.FallbackInfo, + ) + geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_geocoding_results.GeocodingResults, + ) + + +class ComputeRouteMatrixRequest(proto.Message): + r"""ComputeRouteMatrix request message + + Attributes: + origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): + Required. Array of origins, which determines the rows of the + response matrix. Several size restrictions apply to the + cardinality of origins and destinations: + + - The number of elements (origins × destinations) must be + no greater than 625 in any case. + - The number of elements (origins × destinations) must be + no greater than 100 if routing_preference is set to + ``TRAFFIC_AWARE_OPTIMAL``. + - The number of waypoints (origins + destinations) + specified as ``place_id`` must be no greater than 50. + destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): + Required. Array of destinations, which + determines the columns of the response matrix. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, an error is returned. You can specify + this option only when the ``travel_mode`` is ``DRIVE`` or + ``TWO_WHEELER``, otherwise the request fails. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't + set this value, this defaults to the time that + you made the request. If you set this value to a + time that has already occurred, the request + fails. + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + """ + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the matrix element(s). + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + + origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteMatrixOrigin', + ) + destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='RouteMatrixDestination', + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=3, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=4, + enum=gmr_routing_preference.RoutingPreference, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=ExtraComputation, + ) + + +class RouteMatrixOrigin(proto.Message): + r"""A single origin for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. Modifiers for every route that + takes this as the origin + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_route_modifiers.RouteModifiers, + ) + + +class RouteMatrixDestination(proto.Message): + r"""A single destination for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + + +class RouteMatrixElement(proto.Message): + r"""Encapsulates route information computed for an + origin/destination pair in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + origin_index (int): + Zero-based index of the origin in the + request. + + This field is a member of `oneof`_ ``_origin_index``. + destination_index (int): + Zero-based index of the destination in the + request. + + This field is a member of `oneof`_ ``_destination_index``. + status (google.rpc.status_pb2.Status): + Error status code for this element. + condition (google.maps.routing_v2.types.RouteMatrixElementCondition): + Indicates whether the route was found or not. + Independent of status. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this + value is the same as ``static_duration``. If you set the + ``routing_preference`` to either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the route + without taking traffic conditions into + consideration. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. For + example: restriction information and toll + information + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route with the given preferences for + this particular origin/destination pair, it may + fall back to using a different mode of + computation. When fallback mode is used, this + field contains detailed information about the + fallback response. Otherwise this field is + unset. + """ + + origin_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + destination_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + condition: 'RouteMatrixElementCondition' = proto.Field( + proto.ENUM, + number=9, + enum='RouteMatrixElementCondition', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=4, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + travel_advisory: route.RouteTravelAdvisory = proto.Field( + proto.MESSAGE, + number=7, + message=route.RouteTravelAdvisory, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=8, + message=gmr_fallback_info.FallbackInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py new file mode 100644 index 000000000000..d7d3a75786b1 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RoutingPreference', + }, +) + + +class RoutingPreference(proto.Enum): + r"""A set of values that specify factors to take into + consideration when calculating the route. + + Values: + ROUTING_PREFERENCE_UNSPECIFIED (0): + No routing preference specified. Default to + ``TRAFFIC_UNAWARE``. + TRAFFIC_UNAWARE (1): + Computes routes without taking live traffic conditions into + consideration. Suitable when traffic conditions don't matter + or are not applicable. Using this value produces the lowest + latency. Note: For ``RouteTravelMode`` DRIVE and TWO_WHEELER + choice of route and duration are based on road network and + average time-independent traffic conditions. Results for a + given request may vary over time due to changes in the road + network, updated average traffic conditions, and the + distributed nature of the service. Results may also vary + between nearly-equivalent routes at any time or frequency. + TRAFFIC_AWARE (2): + Calculates routes taking live traffic conditions into + consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, + some optimizations are applied to significantly reduce + latency. + TRAFFIC_AWARE_OPTIMAL (3): + Calculates the routes taking live traffic + conditions into consideration, without applying + most performance optimizations. Using this value + produces the highest latency. + """ + ROUTING_PREFERENCE_UNSPECIFIED = 0 + TRAFFIC_UNAWARE = 1 + TRAFFIC_AWARE = 2 + TRAFFIC_AWARE_OPTIMAL = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py new file mode 100644 index 000000000000..9a322fff1e94 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'SpeedReadingInterval', + }, +) + + +class SpeedReadingInterval(proto.Message): + r"""Traffic density indicator on a contiguous segment of a polyline or + path. Given a path with points P_0, P_1, ... , P_N (zero-based + index), the SpeedReadingInterval defines an interval and describes + its traffic using the following categories. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_polyline_point_index (int): + The starting index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_start_polyline_point_index``. + end_polyline_point_index (int): + The ending index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_end_polyline_point_index``. + speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): + Traffic speed in this interval. + """ + class Speed(proto.Enum): + r"""The classification of polyline speed based on traffic data. + + Values: + SPEED_UNSPECIFIED (0): + Default value. This value is unused. + NORMAL (1): + Normal speed, no slowdown is detected. + SLOW (2): + Slowdown detected, but no traffic jam formed. + TRAFFIC_JAM (3): + Traffic jam detected. + """ + SPEED_UNSPECIFIED = 0 + NORMAL = 1 + SLOW = 2 + TRAFFIC_JAM = 3 + + start_polyline_point_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + end_polyline_point_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + speed: Speed = proto.Field( + proto.ENUM, + number=3, + enum=Speed, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py new file mode 100644 index 000000000000..3182bd03ac01 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.type import money_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TollInfo', + }, +) + + +class TollInfo(proto.Message): + r"""Encapsulates toll information on a ``Route`` or on a ``RouteLeg``. + + Attributes: + estimated_price (MutableSequence[google.type.money_pb2.Money]): + The monetary amount of tolls for the + corresponding Route or RouteLeg. This list + contains a money amount for each currency that + is expected to be charged by the toll stations. + Typically this list will contain only one item + for routes with tolls in one currency. For + international trips, this list may contain + multiple items to reflect tolls in different + currencies. + """ + + estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=money_pb2.Money, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py new file mode 100644 index 000000000000..05edb1a082c3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py @@ -0,0 +1,348 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TollPass', + }, +) + + +class TollPass(proto.Enum): + r"""List of toll passes around the world that we support. + + Values: + TOLL_PASS_UNSPECIFIED (0): + Not used. If this value is used, then the + request fails. + AU_ETOLL_TAG (82): + Sydney toll pass. See additional details at + https://www.myetoll.com.au. + AU_EWAY_TAG (83): + Sydney toll pass. See additional details at + https://www.tollpay.com.au. + AU_LINKT (2): + Australia-wide toll pass. + See additional details at + https://www.linkt.com.au/. + AR_TELEPASE (3): + Argentina toll pass. See additional details + at https://telepase.com.ar + BR_AUTO_EXPRESO (81): + Brazil toll pass. See additional details at + https://www.autoexpreso.com + BR_CONECTCAR (7): + Brazil toll pass. See additional details at + https://conectcar.com. + BR_MOVE_MAIS (8): + Brazil toll pass. See additional details at + https://movemais.com. + BR_PASSA_RAPIDO (88): + Brazil toll pass. See additional details at + https://pasorapido.gob.do/ + BR_SEM_PARAR (9): + Brazil toll pass. See additional details at + https://www.semparar.com.br. + BR_TAGGY (10): + Brazil toll pass. See additional details at + https://taggy.com.br. + BR_VELOE (11): + Brazil toll pass. See additional details at + https://veloe.com.br/site/onde-usar. + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): + Canada to United States border crossing. + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): + Canada to United States border crossing. + CA_US_BLUE_WATER_EDGE_PASS (18): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_CONNEXION (19): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_NEXUS_CARD (20): + Canada to United States border crossing. + ID_E_TOLL (16): + Indonesia. + E-card provided by multiple banks used to pay + for tolls. All e-cards via banks are charged the + same so only one enum value is needed. E.g. - + Bank Mandiri + https://www.bankmandiri.co.id/e-money - BCA + https://www.bca.co.id/flazz + - BNI + https://www.bni.co.id/id-id/ebanking/tapcash + IN_FASTAG (78): + India. + IN_LOCAL_HP_PLATE_EXEMPT (79): + India, HP state plate exemption. + MX_IAVE (90): + Mexico toll pass. + https://iave.capufe.gob.mx/#/ + MX_PASE (91): + Mexico + https://www.pase.com.mx + MX_QUICKPASS (93): + Mexico + https://operadoravial.com/quick-pass/ + MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): + http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf + MX_TAG_IAVE (12): + Mexico + MX_TAG_TELEVIA (13): + Mexico toll pass company. One of many + operating in Mexico City. See additional details + at https://www.televia.com.mx. + MX_TELEVIA (92): + Mexico toll pass company. One of many + operating in Mexico City. + https://www.televia.com.mx + MX_VIAPASS (14): + Mexico toll pass. See additional details at + https://www.viapass.com.mx/viapass/web_home.aspx. + US_AL_FREEDOM_PASS (21): + AL, USA. + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): + AK, USA. + US_CA_FASTRAK (4): + CA, USA. + US_CA_FASTRAK_CAV_STICKER (86): + Indicates driver has any FasTrak pass in + addition to the DMV issued Clean Air Vehicle + (CAV) sticker. + https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml + US_CO_EXPRESSTOLL (23): + CO, USA. + US_CO_GO_PASS (24): + CO, USA. + US_DE_EZPASSDE (25): + DE, USA. + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): + FL, USA. + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): + FL, USA. + US_FL_EPASS (67): + FL, USA. + US_FL_GIBA_TOLL_PASS (68): + FL, USA. + US_FL_LEEWAY (69): + FL, USA. + US_FL_SUNPASS (70): + FL, USA. + US_FL_SUNPASS_PRO (71): + FL, USA. + US_IL_EZPASSIL (73): + IL, USA. + US_IL_IPASS (72): + IL, USA. + US_IN_EZPASSIN (26): + IN, USA. + US_KS_BESTPASS_HORIZON (27): + KS, USA. + US_KS_KTAG (28): + KS, USA. + US_KS_NATIONALPASS (29): + KS, USA. + US_KS_PREPASS_ELITEPASS (30): + KS, USA. + US_KY_RIVERLINK (31): + KY, USA. + US_LA_GEAUXPASS (32): + LA, USA. + US_LA_TOLL_TAG (33): + LA, USA. + US_MA_EZPASSMA (6): + MA, USA. + US_MD_EZPASSMD (34): + MD, USA. + US_ME_EZPASSME (35): + ME, USA. + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): + MI, USA. + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): + MI, USA. + US_MI_IQ_PROX_CARD (38): + MI, USA. + US_MI_MACKINAC_BRIDGE_MAC_PASS (39): + MI, USA. + US_MI_NEXPRESS_TOLL (40): + MI, USA. + US_MN_EZPASSMN (41): + MN, USA. + US_NC_EZPASSNC (42): + NC, USA. + US_NC_PEACH_PASS (87): + NC, USA. + US_NC_QUICK_PASS (43): + NC, USA. + US_NH_EZPASSNH (80): + NH, USA. + US_NJ_DOWNBEACH_EXPRESS_PASS (75): + NJ, USA. + US_NJ_EZPASSNJ (74): + NJ, USA. + US_NY_EXPRESSPASS (76): + NY, USA. + US_NY_EZPASSNY (77): + NY, USA. + US_OH_EZPASSOH (44): + OH, USA. + US_PA_EZPASSPA (45): + PA, USA. + US_RI_EZPASSRI (46): + RI, USA. + US_SC_PALPASS (47): + SC, USA. + US_TX_BANCPASS (48): + TX, USA. + US_TX_DEL_RIO_PASS (49): + TX, USA. + US_TX_EFAST_PASS (50): + TX, USA. + US_TX_EAGLE_PASS_EXPRESS_CARD (51): + TX, USA. + US_TX_EPTOLL (52): + TX, USA. + US_TX_EZ_CROSS (53): + TX, USA. + US_TX_EZTAG (54): + TX, USA. + US_TX_LAREDO_TRADE_TAG (55): + TX, USA. + US_TX_PLUSPASS (56): + TX, USA. + US_TX_TOLLTAG (57): + TX, USA. + US_TX_TXTAG (58): + TX, USA. + US_TX_XPRESS_CARD (59): + TX, USA. + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): + UT, USA. + US_VA_EZPASSVA (61): + VA, USA. + US_WA_BREEZEBY (17): + WA, USA. + US_WA_GOOD_TO_GO (1): + WA, USA. + US_WV_EZPASSWV (62): + WV, USA. + US_WV_MEMORIAL_BRIDGE_TICKETS (63): + WV, USA. + US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): + WV, USA. + """ + TOLL_PASS_UNSPECIFIED = 0 + AU_ETOLL_TAG = 82 + AU_EWAY_TAG = 83 + AU_LINKT = 2 + AR_TELEPASE = 3 + BR_AUTO_EXPRESO = 81 + BR_CONECTCAR = 7 + BR_MOVE_MAIS = 8 + BR_PASSA_RAPIDO = 88 + BR_SEM_PARAR = 9 + BR_TAGGY = 10 + BR_VELOE = 11 + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 + CA_US_BLUE_WATER_EDGE_PASS = 18 + CA_US_CONNEXION = 19 + CA_US_NEXUS_CARD = 20 + ID_E_TOLL = 16 + IN_FASTAG = 78 + IN_LOCAL_HP_PLATE_EXEMPT = 79 + MX_IAVE = 90 + MX_PASE = 91 + MX_QUICKPASS = 93 + MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 + MX_TAG_IAVE = 12 + MX_TAG_TELEVIA = 13 + MX_TELEVIA = 92 + MX_VIAPASS = 14 + US_AL_FREEDOM_PASS = 21 + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 + US_CA_FASTRAK = 4 + US_CA_FASTRAK_CAV_STICKER = 86 + US_CO_EXPRESSTOLL = 23 + US_CO_GO_PASS = 24 + US_DE_EZPASSDE = 25 + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 + US_FL_EPASS = 67 + US_FL_GIBA_TOLL_PASS = 68 + US_FL_LEEWAY = 69 + US_FL_SUNPASS = 70 + US_FL_SUNPASS_PRO = 71 + US_IL_EZPASSIL = 73 + US_IL_IPASS = 72 + US_IN_EZPASSIN = 26 + US_KS_BESTPASS_HORIZON = 27 + US_KS_KTAG = 28 + US_KS_NATIONALPASS = 29 + US_KS_PREPASS_ELITEPASS = 30 + US_KY_RIVERLINK = 31 + US_LA_GEAUXPASS = 32 + US_LA_TOLL_TAG = 33 + US_MA_EZPASSMA = 6 + US_MD_EZPASSMD = 34 + US_ME_EZPASSME = 35 + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 + US_MI_IQ_PROX_CARD = 38 + US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 + US_MI_NEXPRESS_TOLL = 40 + US_MN_EZPASSMN = 41 + US_NC_EZPASSNC = 42 + US_NC_PEACH_PASS = 87 + US_NC_QUICK_PASS = 43 + US_NH_EZPASSNH = 80 + US_NJ_DOWNBEACH_EXPRESS_PASS = 75 + US_NJ_EZPASSNJ = 74 + US_NY_EXPRESSPASS = 76 + US_NY_EZPASSNY = 77 + US_OH_EZPASSOH = 44 + US_PA_EZPASSPA = 45 + US_RI_EZPASSRI = 46 + US_SC_PALPASS = 47 + US_TX_BANCPASS = 48 + US_TX_DEL_RIO_PASS = 49 + US_TX_EFAST_PASS = 50 + US_TX_EAGLE_PASS_EXPRESS_CARD = 51 + US_TX_EPTOLL = 52 + US_TX_EZ_CROSS = 53 + US_TX_EZTAG = 54 + US_TX_LAREDO_TRADE_TAG = 55 + US_TX_PLUSPASS = 56 + US_TX_TOLLTAG = 57 + US_TX_TXTAG = 58 + US_TX_XPRESS_CARD = 59 + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 + US_VA_EZPASSVA = 61 + US_WA_BREEZEBY = 17 + US_WA_GOOD_TO_GO = 1 + US_WV_EZPASSWV = 62 + US_WV_MEMORIAL_BRIDGE_TICKETS = 63 + US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py new file mode 100644 index 000000000000..93cfaf1ee04c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Units', + }, +) + + +class Units(proto.Enum): + r"""A set of values that specify the unit of measure used in the + display. + + Values: + UNITS_UNSPECIFIED (0): + Units of measure not specified. Defaults to + the unit of measure inferred from the request. + METRIC (1): + Metric units of measure. + IMPERIAL (2): + Imperial (English) units of measure. + """ + UNITS_UNSPECIFIED = 0 + METRIC = 1 + IMPERIAL = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py new file mode 100644 index 000000000000..a94a99025c80 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'VehicleEmissionType', + }, +) + + +class VehicleEmissionType(proto.Enum): + r"""A set of values describing the vehicle's emission type. + Applies only to the DRIVE travel mode. + + Values: + VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): + No emission type specified. Default to + GASOLINE. + GASOLINE (1): + Gasoline/petrol fueled vehicle. + ELECTRIC (2): + Electricity powered vehicle. + HYBRID (3): + Hybrid fuel (such as gasoline + electric) + vehicle. + DIESEL (4): + Diesel fueled vehicle. + """ + VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 + GASOLINE = 1 + ELECTRIC = 2 + HYBRID = 3 + DIESEL = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py new file mode 100644 index 000000000000..2d71bb0a70a0 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import vehicle_emission_type + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'VehicleInfo', + }, +) + + +class VehicleInfo(proto.Message): + r"""Encapsulates the vehicle information, such as the license + plate last character. + + Attributes: + emission_type (google.maps.routing_v2.types.VehicleEmissionType): + Describes the vehicle's emission type. + Applies only to the DRIVE travel mode. + """ + + emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( + proto.ENUM, + number=2, + enum=vehicle_emission_type.VehicleEmissionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py new file mode 100644 index 000000000000..c25013cfd086 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import location as gmr_location + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Waypoint', + }, +) + + +class Waypoint(proto.Message): + r"""Encapsulates a waypoint. Waypoints mark both the beginning + and end of a route, and include intermediate stops along the + route. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location (google.maps.routing_v2.types.Location): + A point specified using geographic + coordinates, including an optional heading. + + This field is a member of `oneof`_ ``location_type``. + place_id (str): + The POI Place ID associated with the + waypoint. + + This field is a member of `oneof`_ ``location_type``. + address (str): + Human readable address or a plus code. + See https://plus.codes for details. + + This field is a member of `oneof`_ ``location_type``. + via (bool): + Marks this waypoint as a milestone rather a stopping point. + For each non-via waypoint in the request, the response + appends an entry to the ``legs`` array to provide the + details for stopovers on that leg of the trip. Set this + value to true when you want the route to pass through this + waypoint without stopping over. Via waypoints don't cause an + entry to be added to the ``legs`` array, but they do route + the journey through the waypoint. You can only set this + value on waypoints that are intermediates. The request fails + if you set this field on terminal waypoints. If + ``ComputeRoutesRequest.optimize_waypoint_order`` is set to + true then this field cannot be set to true; otherwise, the + request fails. + vehicle_stopover (bool): + Indicates that the waypoint is meant for vehicles to stop + at, where the intention is to either pickup or drop-off. + When you set this value, the calculated route won't include + non-\ ``via`` waypoints on roads that are unsuitable for + pickup and drop-off. This option works only for ``DRIVE`` + and ``TWO_WHEELER`` travel modes, and when the + ``location_type`` is ``location``. + side_of_road (bool): + Indicates that the location of this waypoint is meant to + have a preference for the vehicle to stop at a particular + side of road. When you set this value, the route will pass + through the location so that the vehicle can stop at the + side of road that the location is biased towards from the + center of the road. This option works only for 'DRIVE' and + 'TWO_WHEELER' travel modes. + """ + + location: gmr_location.Location = proto.Field( + proto.MESSAGE, + number=1, + oneof='location_type', + message=gmr_location.Location, + ) + place_id: str = proto.Field( + proto.STRING, + number=2, + oneof='location_type', + ) + address: str = proto.Field( + proto.STRING, + number=7, + oneof='location_type', + ) + via: bool = proto.Field( + proto.BOOL, + number=3, + ) + vehicle_stopover: bool = proto.Field( + proto.BOOL, + number=4, + ) + side_of_road: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py new file mode 100644 index 000000000000..59757e684c85 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/routing_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py new file mode 100644 index 000000000000..381f53f7a26e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py new file mode 100644 index 000000000000..125691404b0b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py new file mode 100644 index 000000000000..c978c3e55cd7 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py new file mode 100644 index 000000000000..ca13730e4ddc --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json new file mode 100644 index 000000000000..b5ed5aca319c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json @@ -0,0 +1,321 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.routing.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-maps-routing", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_route_matrix_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_route_matrix_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_routes_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py new file mode 100644 index 000000000000..291c4ea93db5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class routingCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'extra_computations', ), + 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'units', 'requested_reference_routes', 'extra_computations', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=routingCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the routing client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py new file mode 100644 index 000000000000..1047dfef360b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-maps-routing' + + +description = "Google Maps Routing API client library" + +version = {} +with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-maps-routing" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.maps"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt new file mode 100644 index 000000000000..6c44adfea7ee --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py new file mode 100644 index 000000000000..55f7b3a4ba31 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py @@ -0,0 +1,1750 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.maps.routing_v2.services.routes import RoutesAsyncClient +from google.maps.routing_v2.services.routes import RoutesClient +from google.maps.routing_v2.services.routes import transports +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routes_service +from google.maps.routing_v2.types import routing_preference +from google.maps.routing_v2.types import toll_passes +from google.maps.routing_v2.types import units +from google.maps.routing_v2.types import vehicle_emission_type +from google.maps.routing_v2.types import vehicle_info +from google.maps.routing_v2.types import waypoint +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +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 RoutesClient._get_default_mtls_endpoint(None) is None + assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RoutesGrpcTransport, "grpc"), + (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RoutesRestTransport, "rest"), +]) +def test_routes_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +def test_routes_client_get_transport_class(): + transport = RoutesClient.get_transport_class() + available_transports = [ + transports.RoutesGrpcTransport, + transports.RoutesRestTransport, + ] + assert transport in available_transports + + transport = RoutesClient.get_transport_class("grpc") + assert transport == transports.RoutesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +def test_routes_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RoutesClient, transports.RoutesRestTransport, "rest", "true"), + (RoutesClient, transports.RoutesRestTransport, "rest", "false"), +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_routes_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + RoutesClient, RoutesAsyncClient +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +def test_routes_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +def test_routes_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RoutesClient, transports.RoutesRestTransport, "rest", None), +]) +def test_routes_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_routes_client_client_options_from_dict(): + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RoutesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_routes_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "routes.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes(request_type, transport: str = 'grpc'): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = routes_service.ComputeRoutesResponse( + ) + response = client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + client.compute_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + +@pytest.mark.asyncio +async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( + )) + response = await client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +@pytest.mark.asyncio +async def test_compute_routes_async_from_dict(): + await test_compute_routes_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix(request_type, transport: str = 'grpc'): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([routes_service.RouteMatrixElement()]) + response = client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, routes_service.RouteMatrixElement) + + +def test_compute_route_matrix_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + client.compute_route_matrix() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + +@pytest.mark.asyncio +async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) + response = await client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, routes_service.RouteMatrixElement) + + +@pytest.mark.asyncio +async def test_compute_route_matrix_async_from_dict(): + await test_compute_route_matrix_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes_rest(request_type): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = routes_service.ComputeRoutesResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.compute_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): + transport_class = transports.RoutesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.ComputeRoutesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.compute_routes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_routes_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_routes._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_routes_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) + + request = routes_service.ComputeRoutesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.ComputeRoutesResponse() + + client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_routes_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRoutesRequest): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.compute_routes(request) + + +def test_compute_routes_rest_error(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix_rest(request_type): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = routes_service.RouteMatrixElement( + origin_index=1279, + destination_index=1817, + condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, + distance_meters=1594, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.compute_route_matrix(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.RouteMatrixElement) + assert response.origin_index == 1279 + assert response.destination_index == 1817 + assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS + assert response.distance_meters == 1594 + + +def test_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): + transport_class = transports.RoutesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.RouteMatrixElement() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.compute_route_matrix(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_route_matrix_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_route_matrix_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) + req.return_value._content = "[{}]".format(req.return_value._content) + + request = routes_service.ComputeRouteMatrixRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.RouteMatrixElement() + + client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_route_matrix_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.compute_route_matrix(request) + + +def test_compute_route_matrix_rest_error(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutesClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RoutesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RoutesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = RoutesClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RoutesGrpcTransport, + ) + +def test_routes_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_routes_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'compute_routes', + 'compute_route_matrix', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_routes_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +def test_routes_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport() + adc.assert_called_once() + + +def test_routes_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RoutesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + ], +) +def test_routes_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, + ], +) +def test_routes_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RoutesGrpcTransport, grpc_helpers), + (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_routes_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "routes.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_routes_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.RoutesRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_routes_host_no_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_routes_host_with_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_routes_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RoutesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RoutesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.compute_routes._session + session2 = client2.transport.compute_routes._session + assert session1 != session2 + session1 = client1.transport.compute_route_matrix._session + session2 = client2.transport.compute_route_matrix._session + assert session1 != session2 +def test_routes_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_routes_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + 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 + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + 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=cred, + credentials_file=None, + scopes=None, + 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 + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_transport_channel_mtls_with_adc( + transport_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), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + 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 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RoutesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RoutesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = RoutesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RoutesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RoutesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RoutesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = RoutesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RoutesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RoutesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RoutesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: + transport_class = RoutesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (RoutesClient, transports.RoutesGrpcTransport), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From 33718e94f339f3a78f665ef5e21a0d917cf12027 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 9 Mar 2023 19:51:28 +0000 Subject: [PATCH 02/12] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../google-maps-routing/v2/.coveragerc | 13 - .../google-maps-routing/v2/.flake8 | 33 - .../google-maps-routing/v2/MANIFEST.in | 2 - .../google-maps-routing/v2/README.rst | 49 - .../google-maps-routing/v2/docs/conf.py | 376 ---- .../google-maps-routing/v2/docs/index.rst | 7 - .../v2/docs/routing_v2/routes.rst | 6 - .../v2/docs/routing_v2/services.rst | 6 - .../v2/docs/routing_v2/types.rst | 6 - .../v2/google/maps/routing/__init__.py | 97 - .../v2/google/maps/routing/gapic_version.py | 16 - .../v2/google/maps/routing/py.typed | 2 - .../v2/google/maps/routing_v2/__init__.py | 98 - .../maps/routing_v2/gapic_metadata.json | 58 - .../google/maps/routing_v2/gapic_version.py | 16 - .../v2/google/maps/routing_v2/py.typed | 2 - .../maps/routing_v2/services/__init__.py | 15 - .../routing_v2/services/routes/__init__.py | 22 - .../services/routes/async_client.py | 416 ---- .../maps/routing_v2/services/routes/client.py | 613 ------ .../services/routes/transports/__init__.py | 38 - .../services/routes/transports/base.py | 161 -- .../services/routes/transports/grpc.py | 363 ---- .../routes/transports/grpc_asyncio.py | 362 ---- .../services/routes/transports/rest.py | 417 ---- .../google/maps/routing_v2/types/__init__.py | 105 - .../maps/routing_v2/types/fallback_info.py | 103 - .../google/maps/routing_v2/types/location.py | 62 - .../google/maps/routing_v2/types/maneuver.py | 96 - .../types/navigation_instruction.py | 58 - .../google/maps/routing_v2/types/polyline.py | 113 -- .../v2/google/maps/routing_v2/types/route.py | 409 ---- .../maps/routing_v2/types/route_label.py | 57 - .../maps/routing_v2/types/route_modifiers.py | 97 - .../routing_v2/types/route_travel_mode.py | 59 - .../maps/routing_v2/types/routes_service.py | 510 ----- .../routing_v2/types/routing_preference.py | 67 - .../types/speed_reading_interval.py | 89 - .../google/maps/routing_v2/types/toll_info.py | 56 - .../maps/routing_v2/types/toll_passes.py | 348 ---- .../v2/google/maps/routing_v2/types/units.py | 49 - .../routing_v2/types/vehicle_emission_type.py | 56 - .../maps/routing_v2/types/vehicle_info.py | 50 - .../google/maps/routing_v2/types/waypoint.py | 123 -- .../google-maps-routing/v2/mypy.ini | 3 - .../google-maps-routing/v2/noxfile.py | 184 -- ...rated_routes_compute_route_matrix_async.py | 52 - ...erated_routes_compute_route_matrix_sync.py | 52 - ...2_generated_routes_compute_routes_async.py | 51 - ...v2_generated_routes_compute_routes_sync.py | 51 - ...ippet_metadata_google.maps.routing.v2.json | 321 --- .../v2/scripts/fixup_routing_v2_keywords.py | 177 -- .../google-maps-routing/v2/setup.py | 90 - .../v2/testing/constraints-3.10.txt | 6 - .../v2/testing/constraints-3.11.txt | 6 - .../v2/testing/constraints-3.12.txt | 6 - .../v2/testing/constraints-3.7.txt | 9 - .../v2/testing/constraints-3.8.txt | 6 - .../v2/testing/constraints-3.9.txt | 6 - .../google-maps-routing/v2/tests/__init__.py | 16 - .../v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/routing_v2/__init__.py | 16 - .../unit/gapic/routing_v2/test_routes.py | 1750 ----------------- .../google/maps/routing/__init__.py | 6 + .../google/maps/routing_v2/__init__.py | 3 + .../services/routes/async_client.py | 7 +- .../maps/routing_v2/services/routes/client.py | 7 +- .../google/maps/routing_v2/types/__init__.py | 3 + .../routing_v2/types/geocoding_results.py | 22 +- .../google/maps/routing_v2/types/route.py | 22 +- .../maps/routing_v2/types/routes_service.py | 9 + .../google/maps/routing_v2/types/waypoint.py | 10 + packages/google-maps-routing/setup.py | 1 - .../testing/constraints-3.7.txt | 1 - .../unit/gapic/routing_v2/test_routes.py | 1 + 76 files changed, 59 insertions(+), 8568 deletions(-) delete mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc delete mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 delete mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini delete mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py rename {owl-bot-staging/google-maps-routing/v2 => packages/google-maps-routing}/google/maps/routing_v2/types/geocoding_results.py (91%) diff --git a/owl-bot-staging/google-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc deleted file mode 100644 index d0ce5597b0a9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/routing/__init__.py - google/maps/routing/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.flake8 +++ /dev/null @@ -1,33 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in deleted file mode 100644 index c5b56c111c00..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/routing *.py -recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst deleted file mode 100644 index f0002366e552..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Routing API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Maps Routing API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py deleted file mode 100644 index d7a10abed96b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-maps-routing documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -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"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-maps-routing" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# 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"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# 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 - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -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 = { - "description": "Google Maps Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# 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 - -# 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 - -# 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, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# 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 = [] - -# 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' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is 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 = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# 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' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# 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' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-maps-routing-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- 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', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-maps-routing.tex", - u"google-maps-routing 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 - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# 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 = [ - ( - root_doc, - "google-maps-routing", - u"Google Maps Routing Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-maps-routing", - u"google-maps-routing Documentation", - author, - "google-maps-routing", - "GAPIC library for Google Maps Routing API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# 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), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst deleted file mode 100644 index e2563dd88ee9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - routing_v2/services - routing_v2/types diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst deleted file mode 100644 index 3d52309cddae..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst +++ /dev/null @@ -1,6 +0,0 @@ -Routes ------------------------- - -.. automodule:: google.maps.routing_v2.services.routes - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst deleted file mode 100644 index e96568dc434c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Routing v2 API -======================================= -.. toctree:: - :maxdepth: 2 - - routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst deleted file mode 100644 index 176a5a812cf8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Routing v2 API -==================================== - -.. automodule:: google.maps.routing_v2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py deleted file mode 100644 index 59020a3484c3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.maps.routing import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.routing_v2.services.routes.client import RoutesClient -from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient - -from google.maps.routing_v2.types.fallback_info import FallbackInfo -from google.maps.routing_v2.types.fallback_info import FallbackReason -from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode -from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint -from google.maps.routing_v2.types.geocoding_results import GeocodingResults -from google.maps.routing_v2.types.location import Location -from google.maps.routing_v2.types.maneuver import Maneuver -from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction -from google.maps.routing_v2.types.polyline import Polyline -from google.maps.routing_v2.types.polyline import PolylineEncoding -from google.maps.routing_v2.types.polyline import PolylineQuality -from google.maps.routing_v2.types.route import Route -from google.maps.routing_v2.types.route import RouteLeg -from google.maps.routing_v2.types.route import RouteLegStep -from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory -from google.maps.routing_v2.types.route import RouteLegTravelAdvisory -from google.maps.routing_v2.types.route import RouteTravelAdvisory -from google.maps.routing_v2.types.route_label import RouteLabel -from google.maps.routing_v2.types.route_modifiers import RouteModifiers -from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode -from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse -from google.maps.routing_v2.types.routes_service import RouteMatrixDestination -from google.maps.routing_v2.types.routes_service import RouteMatrixElement -from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin -from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition -from google.maps.routing_v2.types.routing_preference import RoutingPreference -from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval -from google.maps.routing_v2.types.toll_info import TollInfo -from google.maps.routing_v2.types.toll_passes import TollPass -from google.maps.routing_v2.types.units import Units -from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType -from google.maps.routing_v2.types.vehicle_info import VehicleInfo -from google.maps.routing_v2.types.waypoint import Waypoint - -__all__ = ('RoutesClient', - 'RoutesAsyncClient', - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py deleted file mode 100644 index 405b1cebcf15..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py deleted file mode 100644 index cd9d694f63c6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.maps.routing_v2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.routes import RoutesClient -from .services.routes import RoutesAsyncClient - -from .types.fallback_info import FallbackInfo -from .types.fallback_info import FallbackReason -from .types.fallback_info import FallbackRoutingMode -from .types.geocoding_results import GeocodedWaypoint -from .types.geocoding_results import GeocodingResults -from .types.location import Location -from .types.maneuver import Maneuver -from .types.navigation_instruction import NavigationInstruction -from .types.polyline import Polyline -from .types.polyline import PolylineEncoding -from .types.polyline import PolylineQuality -from .types.route import Route -from .types.route import RouteLeg -from .types.route import RouteLegStep -from .types.route import RouteLegStepTravelAdvisory -from .types.route import RouteLegTravelAdvisory -from .types.route import RouteTravelAdvisory -from .types.route_label import RouteLabel -from .types.route_modifiers import RouteModifiers -from .types.route_travel_mode import RouteTravelMode -from .types.routes_service import ComputeRouteMatrixRequest -from .types.routes_service import ComputeRoutesRequest -from .types.routes_service import ComputeRoutesResponse -from .types.routes_service import RouteMatrixDestination -from .types.routes_service import RouteMatrixElement -from .types.routes_service import RouteMatrixOrigin -from .types.routes_service import RouteMatrixElementCondition -from .types.routing_preference import RoutingPreference -from .types.speed_reading_interval import SpeedReadingInterval -from .types.toll_info import TollInfo -from .types.toll_passes import TollPass -from .types.units import Units -from .types.vehicle_emission_type import VehicleEmissionType -from .types.vehicle_info import VehicleInfo -from .types.waypoint import Waypoint - -__all__ = ( - 'RoutesAsyncClient', -'ComputeRouteMatrixRequest', -'ComputeRoutesRequest', -'ComputeRoutesResponse', -'FallbackInfo', -'FallbackReason', -'FallbackRoutingMode', -'GeocodedWaypoint', -'GeocodingResults', -'Location', -'Maneuver', -'NavigationInstruction', -'Polyline', -'PolylineEncoding', -'PolylineQuality', -'Route', -'RouteLabel', -'RouteLeg', -'RouteLegStep', -'RouteLegStepTravelAdvisory', -'RouteLegTravelAdvisory', -'RouteMatrixDestination', -'RouteMatrixElement', -'RouteMatrixElementCondition', -'RouteMatrixOrigin', -'RouteModifiers', -'RouteTravelAdvisory', -'RouteTravelMode', -'RoutesClient', -'RoutingPreference', -'SpeedReadingInterval', -'TollInfo', -'TollPass', -'Units', -'VehicleEmissionType', -'VehicleInfo', -'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json deleted file mode 100644 index 8382cea1d39a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json +++ /dev/null @@ -1,58 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.routing_v2", - "protoPackage": "google.maps.routing.v2", - "schema": "1.0", - "services": { - "Routes": { - "clients": { - "grpc": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RoutesAsyncClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "rest": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py deleted file mode 100644 index 405b1cebcf15..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py deleted file mode 100644 index e8e1c3845db5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py deleted file mode 100644 index ff3f8f71863f..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import RoutesClient -from .async_client import RoutesAsyncClient - -__all__ = ( - 'RoutesClient', - 'RoutesAsyncClient', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py deleted file mode 100644 index 7f8df74a140b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union - -from google.maps.routing_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .client import RoutesClient - - -class RoutesAsyncClient: - """The Routes API.""" - - _client: RoutesClient - - DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RoutesClient.common_folder_path) - parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) - common_organization_path = staticmethod(RoutesClient.common_organization_path) - parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) - common_project_path = staticmethod(RoutesClient.common_project_path) - parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) - common_location_path = staticmethod(RoutesClient.common_location_path) - parse_common_location_path = staticmethod(RoutesClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(RoutesClient).get_transport_class, type(RoutesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, RoutesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.RoutesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RoutesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # Create or coerce a protobuf request object. - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.compute_routes, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - # Create or coerce a protobuf request object. - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.compute_route_matrix, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RoutesAsyncClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py deleted file mode 100644 index 1943383c7246..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py +++ /dev/null @@ -1,613 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast - -from google.maps.routing_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RoutesGrpcTransport -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .transports.rest import RoutesRestTransport - - -class RoutesClientMeta(type): - """Metaclass for the Routes client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] - _transport_registry["grpc"] = RoutesGrpcTransport - _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport - _transport_registry["rest"] = RoutesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RoutesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class RoutesClient(metaclass=RoutesClientMeta): - """The Routes API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "routes.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RoutesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, RoutesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, RoutesTransport): - # transport is a RoutesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a routes_service.ComputeRoutesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, routes_service.ComputeRoutesRequest): - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_routes] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[routes_service.RouteMatrixElement]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - Iterable[google.maps.routing_v2.types.RouteMatrixElement]: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a routes_service.ComputeRouteMatrixRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, routes_service.ComputeRouteMatrixRequest): - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "RoutesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RoutesClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py deleted file mode 100644 index a15967f001c9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import RoutesTransport -from .grpc import RoutesGrpcTransport -from .grpc_asyncio import RoutesGrpcAsyncIOTransport -from .rest import RoutesRestTransport -from .rest import RoutesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] -_transport_registry['grpc'] = RoutesGrpcTransport -_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport -_transport_registry['rest'] = RoutesRestTransport - -__all__ = ( - 'RoutesTransport', - 'RoutesGrpcTransport', - 'RoutesGrpcAsyncIOTransport', - 'RoutesRestTransport', - 'RoutesRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py deleted file mode 100644 index a6fa68993eca..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py +++ /dev/null @@ -1,161 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.maps.routing_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.maps.routing_v2.types import routes_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class RoutesTransport(abc.ABC): - """Abstract transport class for Routes.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'routes.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.compute_routes: gapic_v1.method.wrap_method( - self.compute_routes, - default_timeout=None, - client_info=client_info, - ), - self.compute_route_matrix: gapic_v1.method.wrap_method( - self.compute_route_matrix, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Union[ - routes_service.ComputeRoutesResponse, - Awaitable[routes_service.ComputeRoutesResponse] - ]]: - raise NotImplementedError() - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Union[ - routes_service.RouteMatrixElement, - Awaitable[routes_service.RouteMatrixElement] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RoutesTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py deleted file mode 100644 index 8316c8b03587..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py +++ /dev/null @@ -1,363 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO - - -class RoutesGrpcTransport(RoutesTransport): - """gRPC backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - ~.ComputeRoutesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self.grpc_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - ~.RouteMatrixElement]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RoutesGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py deleted file mode 100644 index 752c5eaefc33..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py +++ /dev/null @@ -1,362 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO -from .grpc import RoutesGrpcTransport - - -class RoutesGrpcAsyncIOTransport(RoutesTransport): - """gRPC AsyncIO backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Awaitable[routes_service.ComputeRoutesResponse]]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - Awaitable[~.ComputeRoutesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self.grpc_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Awaitable[routes_service.RouteMatrixElement]]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - Awaitable[~.RouteMatrixElement]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'RoutesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py deleted file mode 100644 index c7fdf524b0c7..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.maps.routing_v2.types import routes_service - -from .base import RoutesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class RoutesRestInterceptor: - """Interceptor for Routes. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the RoutesRestTransport. - - .. code-block:: python - class MyCustomRoutesInterceptor(RoutesRestInterceptor): - def pre_compute_route_matrix(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_route_matrix(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_compute_routes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_routes(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) - client = RoutesClient(transport=transport) - - - """ - def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: - """Post-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compute_routes - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: - """Post-rpc interceptor for compute_routes - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class RoutesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RoutesRestInterceptor - - -class RoutesRestTransport(RoutesTransport): - """REST backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[RoutesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or RoutesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ComputeRouteMatrix(RoutesRestStub): - def __hash__(self): - return hash("ComputeRouteMatrix") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: routes_service.ComputeRouteMatrixRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> rest_streaming.ResponseIterator: - r"""Call the compute route matrix method over HTTP. - - Args: - request (~.routes_service.ComputeRouteMatrixRequest): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.routes_service.RouteMatrixElement: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/distanceMatrix/v2:computeRouteMatrix', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) - pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) - resp = self._interceptor.post_compute_route_matrix(resp) - return resp - - class _ComputeRoutes(RoutesRestStub): - def __hash__(self): - return hash("ComputeRoutes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: routes_service.ComputeRoutesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> routes_service.ComputeRoutesResponse: - r"""Call the compute routes method over HTTP. - - Args: - request (~.routes_service.ComputeRoutesRequest): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.routes_service.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/directions/v2:computeRoutes', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_compute_routes(request, metadata) - pb_request = routes_service.ComputeRoutesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = routes_service.ComputeRoutesResponse() - pb_resp = routes_service.ComputeRoutesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_compute_routes(resp) - return resp - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RoutesRestTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py deleted file mode 100644 index 7323899cfc30..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .fallback_info import ( - FallbackInfo, - FallbackReason, - FallbackRoutingMode, -) -from .geocoding_results import ( - GeocodedWaypoint, - GeocodingResults, -) -from .location import ( - Location, -) -from .navigation_instruction import ( - NavigationInstruction, -) -from .polyline import ( - Polyline, - PolylineEncoding, - PolylineQuality, -) -from .route import ( - Route, - RouteLeg, - RouteLegStep, - RouteLegStepTravelAdvisory, - RouteLegTravelAdvisory, - RouteTravelAdvisory, -) -from .route_modifiers import ( - RouteModifiers, -) -from .routes_service import ( - ComputeRouteMatrixRequest, - ComputeRoutesRequest, - ComputeRoutesResponse, - RouteMatrixDestination, - RouteMatrixElement, - RouteMatrixOrigin, - RouteMatrixElementCondition, -) -from .speed_reading_interval import ( - SpeedReadingInterval, -) -from .toll_info import ( - TollInfo, -) -from .vehicle_info import ( - VehicleInfo, -) -from .waypoint import ( - Waypoint, -) - -__all__ = ( - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py deleted file mode 100644 index 99670aafac25..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'FallbackReason', - 'FallbackRoutingMode', - 'FallbackInfo', - }, -) - - -class FallbackReason(proto.Enum): - r"""Reasons for using fallback response. - - Values: - FALLBACK_REASON_UNSPECIFIED (0): - No fallback reason specified. - SERVER_ERROR (1): - A server error happened while calculating - routes with your preferred routing mode, but we - were able to return a result calculated by an - alternative mode. - LATENCY_EXCEEDED (2): - We were not able to finish the calculation - with your preferred routing mode on time, but we - were able to return a result calculated by an - alternative mode. - """ - FALLBACK_REASON_UNSPECIFIED = 0 - SERVER_ERROR = 1 - LATENCY_EXCEEDED = 2 - - -class FallbackRoutingMode(proto.Enum): - r"""Actual routing mode used for returned fallback response. - - Values: - FALLBACK_ROUTING_MODE_UNSPECIFIED (0): - Not used. - FALLBACK_TRAFFIC_UNAWARE (1): - Indicates the "TRAFFIC_UNAWARE" routing mode was used to - compute the response. - FALLBACK_TRAFFIC_AWARE (2): - Indicates the "TRAFFIC_AWARE" routing mode was used to - compute the response. - """ - FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 - FALLBACK_TRAFFIC_UNAWARE = 1 - FALLBACK_TRAFFIC_AWARE = 2 - - -class FallbackInfo(proto.Message): - r"""Information related to how and why a fallback result was - used. If this field is set, then it means the server used a - different routing mode from your preferred mode as fallback. - - Attributes: - routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): - Routing mode used for the response. If - fallback was triggered, the mode may be - different from routing preference set in the - original client request. - reason (google.maps.routing_v2.types.FallbackReason): - The reason why fallback response was used - instead of the original response. This field is - only populated when the fallback mode is - triggered and the fallback response is returned. - """ - - routing_mode: 'FallbackRoutingMode' = proto.Field( - proto.ENUM, - number=1, - enum='FallbackRoutingMode', - ) - reason: 'FallbackReason' = proto.Field( - proto.ENUM, - number=2, - enum='FallbackReason', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py deleted file mode 100644 index 722cd7dda46a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Location', - }, -) - - -class Location(proto.Message): - r"""Encapsulates a location (a geographic point, and an optional - heading). - - Attributes: - lat_lng (google.type.latlng_pb2.LatLng): - The waypoint's geographic coordinates. - heading (google.protobuf.wrappers_pb2.Int32Value): - The compass heading associated with the direction of the - flow of traffic. This value is used to specify the side of - the road to use for pickup and drop-off. Heading values can - be from 0 to 360, where 0 specifies a heading of due North, - 90 specifies a heading of due East, etc. You can use this - field only for ``DRIVE`` and ``TWO_WHEELER`` travel modes. - """ - - lat_lng: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - heading: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py deleted file mode 100644 index 60e5cd3cb9c6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Maneuver', - }, -) - - -class Maneuver(proto.Enum): - r"""A set of values that specify the navigation action to take - for the current step (e.g., turn left, merge, straight, etc.). - - Values: - MANEUVER_UNSPECIFIED (0): - Not used. - TURN_SLIGHT_LEFT (1): - Turn slightly to the left. - TURN_SHARP_LEFT (2): - Turn sharply to the left. - UTURN_LEFT (3): - Make a left u-turn. - TURN_LEFT (4): - Turn left. - TURN_SLIGHT_RIGHT (5): - Turn slightly to the right. - TURN_SHARP_RIGHT (6): - Turn sharply to the right. - UTURN_RIGHT (7): - Make a right u-turn. - TURN_RIGHT (8): - Turn right. - STRAIGHT (9): - Go straight. - RAMP_LEFT (10): - Take the left ramp. - RAMP_RIGHT (11): - Take the right ramp. - MERGE (12): - Merge into traffic. - FORK_LEFT (13): - Take the left fork. - FORK_RIGHT (14): - Take the right fork. - FERRY (15): - Take the ferry. - FERRY_TRAIN (16): - Take the train leading onto the ferry. - ROUNDABOUT_LEFT (17): - Turn left at the roundabout. - ROUNDABOUT_RIGHT (18): - Turn right at the roundabout. - """ - MANEUVER_UNSPECIFIED = 0 - TURN_SLIGHT_LEFT = 1 - TURN_SHARP_LEFT = 2 - UTURN_LEFT = 3 - TURN_LEFT = 4 - TURN_SLIGHT_RIGHT = 5 - TURN_SHARP_RIGHT = 6 - UTURN_RIGHT = 7 - TURN_RIGHT = 8 - STRAIGHT = 9 - RAMP_LEFT = 10 - RAMP_RIGHT = 11 - MERGE = 12 - FORK_LEFT = 13 - FORK_RIGHT = 14 - FERRY = 15 - FERRY_TRAIN = 16 - ROUNDABOUT_LEFT = 17 - ROUNDABOUT_RIGHT = 18 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py deleted file mode 100644 index dc8b69e76ccd..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import maneuver as gmr_maneuver - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'NavigationInstruction', - }, -) - - -class NavigationInstruction(proto.Message): - r"""Encapsulates navigation instructions for a - [RouteLegStep][google.maps.routing.v2.RouteLegStep] - - Attributes: - maneuver (google.maps.routing_v2.types.Maneuver): - Encapsulates the navigation instructions for - the current step (e.g., turn left, merge, - straight, etc.). This field determines which - icon to display. - instructions (str): - Instructions for navigating this step. - """ - - maneuver: gmr_maneuver.Maneuver = proto.Field( - proto.ENUM, - number=1, - enum=gmr_maneuver.Maneuver, - ) - instructions: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py deleted file mode 100644 index 4d9630691288..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'PolylineQuality', - 'PolylineEncoding', - 'Polyline', - }, -) - - -class PolylineQuality(proto.Enum): - r"""A set of values that specify the quality of the polyline. - - Values: - POLYLINE_QUALITY_UNSPECIFIED (0): - No polyline quality preference specified. Defaults to - ``OVERVIEW``. - HIGH_QUALITY (1): - Specifies a high-quality polyline - which is composed using - more points than ``OVERVIEW``, at the cost of increased - response size. Use this value when you need more precision. - OVERVIEW (2): - Specifies an overview polyline - which is composed using a - small number of points. Use this value when displaying an - overview of the route. Using this option has a lower request - latency compared to using the ``HIGH_QUALITY`` option. - """ - POLYLINE_QUALITY_UNSPECIFIED = 0 - HIGH_QUALITY = 1 - OVERVIEW = 2 - - -class PolylineEncoding(proto.Enum): - r"""Specifies the preferred type of polyline to be returned. - - Values: - POLYLINE_ENCODING_UNSPECIFIED (0): - No polyline type preference specified. Defaults to - ``ENCODED_POLYLINE``. - ENCODED_POLYLINE (1): - Specifies a polyline encoded using the `polyline encoding - algorithm `__. - GEO_JSON_LINESTRING (2): - Specifies a polyline using the `GeoJSON LineString - format `__ - """ - POLYLINE_ENCODING_UNSPECIFIED = 0 - ENCODED_POLYLINE = 1 - GEO_JSON_LINESTRING = 2 - - -class Polyline(proto.Message): - r"""Encapsulates an encoded polyline. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - encoded_polyline (str): - The string encoding of the polyline using the `polyline - encoding - algorithm `__ - - This field is a member of `oneof`_ ``polyline_type``. - geo_json_linestring (google.protobuf.struct_pb2.Struct): - Specifies a polyline using the `GeoJSON LineString - format `__ - - This field is a member of `oneof`_ ``polyline_type``. - """ - - encoded_polyline: str = proto.Field( - proto.STRING, - number=1, - oneof='polyline_type', - ) - geo_json_linestring: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - oneof='polyline_type', - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py deleted file mode 100644 index 2a57054febff..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py +++ /dev/null @@ -1,409 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.geo.type import viewport_pb2 # type: ignore -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction -from google.maps.routing_v2.types import polyline as gmr_polyline -from google.maps.routing_v2.types import route_label -from google.maps.routing_v2.types import speed_reading_interval -from google.maps.routing_v2.types import toll_info as gmr_toll_info -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Route', - 'RouteTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteLegStepTravelAdvisory', - 'RouteLeg', - 'RouteLegStep', - }, -) - - -class Route(proto.Message): - r"""Encapsulates a route, which consists of a series of connected - road segments that join beginning, ending, and intermediate - waypoints. - - Attributes: - route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): - Labels for the ``Route`` that are useful to identify - specific properties of the route to compare against others. - legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): - A collection of legs (path segments between waypoints) that - make-up the route. Each leg corresponds to the trip between - two non-\ ``via`` Waypoints. For example, a route with no - intermediate waypoints has only one leg. A route that - includes one non-\ ``via`` intermediate waypoint has two - legs. A route that includes one ``via`` intermediate - waypoint has one leg. The order of the legs matches the - order of Waypoints from ``origin`` to ``intermediates`` to - ``destination``. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the route - without taking traffic conditions into - consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall route polyline. This polyline will be the - combined polyline of all ``legs``. - description (str): - A description of the route. - warnings (MutableSequence[str]): - An array of warnings to show when displaying - the route. - viewport (google.geo.type.viewport_pb2.Viewport): - The viewport bounding box of the polyline. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. - route_token (str): - Web-safe base64 encoded route token that can be passed to - NavigationSDK, which allows the Navigation SDK to - reconstruct the route during navigation, and in the event of - rerouting honor the original intention when Routes - ComputeRoutes is called. Customers should treat this token - as an opaque blob. NOTE: ``Route.route_token`` is only - available for requests that have set - ``ComputeRoutesRequest.routing_preference`` to - ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. - ``Route.route_token`` is also not supported for requests - that have Via waypoints. - """ - - route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( - proto.ENUM, - number=13, - enum=route_label.RouteLabel, - ) - legs: MutableSequence['RouteLeg'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteLeg', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=2, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_polyline.Polyline, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - warnings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - viewport: viewport_pb2.Viewport = proto.Field( - proto.MESSAGE, - number=8, - message=viewport_pb2.Viewport, - ) - travel_advisory: 'RouteTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=9, - message='RouteTravelAdvisory', - ) - route_token: str = proto.Field( - proto.STRING, - number=12, - ) - - -class RouteTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction - etc. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Encapsulates information about tolls on the Route. This - field is only populated if we expect there are tolls on the - Route. If this field is set but the estimated_price subfield - is not populated, we expect that road contains tolls but we - do not know an estimated price. If this field is not set, - then we expect there is no toll on the Route. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the route without overlap. The - start point of a specified interval is the same as the end - point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - fuel_consumption_microliters (int): - The fuel consumption prediction in - microliters. - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=speed_reading_interval.SpeedReadingInterval, - ) - fuel_consumption_microliters: int = proto.Field( - proto.INT64, - number=5, - ) - - -class RouteLegTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction - etc. on a route leg. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Encapsulates information about tolls on the specific - RouteLeg. This field is only populated if we expect there - are tolls on the RouteLeg. If this field is set but the - estimated_price subfield is not populated, we expect that - road contains tolls but we do not know an estimated price. - If this field does not exist, then there is no toll on the - RouteLeg. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the RouteLg without overlap. - The start point of a specified interval is the same as the - end point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLegStepTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction on - a leg step. - - Attributes: - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - NOTE: This field is not currently populated. - """ - - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLeg(proto.Message): - r"""Encapsulates a segment between non-\ ``via`` waypoints. - - Attributes: - distance_meters (int): - The travel distance of the route leg, in - meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the leg. If the - ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then - this value is the same as ``static_duration``. If the - ``route_preference`` is either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the leg, - calculated without taking traffic conditions - into consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall polyline for this leg. This includes that each - ``step``'s polyline. - start_location (google.maps.routing_v2.types.Location): - The start location of this leg. This might be different from - the provided ``origin``. For example, when the provided - ``origin`` is not near a road, this is a point on the road. - end_location (google.maps.routing_v2.types.Location): - The end location of this leg. This might be different from - the provided ``destination``. For example, when the provided - ``destination`` is not near a road, this is a point on the - road. - steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): - An array of steps denoting segments within - this leg. Each step represents one navigation - instruction. - travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): - Encapsulates the additional information that - the user should be informed about, such as - possible traffic zone restriction etc. on a - route leg. - """ - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=4, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=6, - message=location.Location, - ) - steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='RouteLegStep', - ) - travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=8, - message='RouteLegTravelAdvisory', - ) - - -class RouteLegStep(proto.Message): - r"""Encapsulates a segment of a ``RouteLeg``. A step corresponds to a - single navigation instruction. Route legs are made up of steps. - - Attributes: - distance_meters (int): - The travel distance of this step, in meters. - In some circumstances, this field might not have - a value. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of travel through this step - without taking traffic conditions into - consideration. In some circumstances, this field - might not have a value. - polyline (google.maps.routing_v2.types.Polyline): - The polyline associated with this step. - start_location (google.maps.routing_v2.types.Location): - The start location of this step. - end_location (google.maps.routing_v2.types.Location): - The end location of this step. - navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): - Navigation instructions. - travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): - Encapsulates the additional information that - the user should be informed about, such as - possible traffic zone restriction on a leg step. - """ - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=4, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( - proto.MESSAGE, - number=6, - message=gmr_navigation_instruction.NavigationInstruction, - ) - travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=7, - message='RouteLegStepTravelAdvisory', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py deleted file mode 100644 index a3e095209d58..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteLabel', - }, -) - - -class RouteLabel(proto.Enum): - r"""Labels for the ``Route`` that are useful to identify specific - properties of the route to compare against others. - - Values: - ROUTE_LABEL_UNSPECIFIED (0): - Default - not used. - DEFAULT_ROUTE (1): - The default "best" route returned for the - route computation. - DEFAULT_ROUTE_ALTERNATE (2): - An alternative to the default "best" route. Routes like this - will be returned when - ``ComputeRoutesRequest.compute_alternative_routes`` is - specified. - FUEL_EFFICIENT (3): - Fuel efficient route. Routes labeled with - this value are determined to be optimized for - Eco parameters such as fuel consumption. - """ - ROUTE_LABEL_UNSPECIFIED = 0 - DEFAULT_ROUTE = 1 - DEFAULT_ROUTE_ALTERNATE = 2 - FUEL_EFFICIENT = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py deleted file mode 100644 index 59f5e6420c4c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import toll_passes as gmr_toll_passes -from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteModifiers', - }, -) - - -class RouteModifiers(proto.Message): - r"""Encapsulates a set of optional conditions to satisfy when - calculating the routes. - - Attributes: - avoid_tolls (bool): - Specifies whether to avoid toll roads where reasonable. - Preference will be given to routes not containing toll - roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - travel modes. - avoid_highways (bool): - Specifies whether to avoid highways where reasonable. - Preference will be given to routes not containing highways. - Applies only to the ``DRIVE`` and ``TWO_WHEELER`` travel - modes. - avoid_ferries (bool): - Specifies whether to avoid ferries where reasonable. - Preference will be given to routes not containing travel by - ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` - travel modes. - avoid_indoor (bool): - Specifies whether to avoid navigating indoors where - reasonable. Preference will be given to routes not - containing indoor navigation. Applies only to the ``WALK`` - travel mode. - vehicle_info (google.maps.routing_v2.types.VehicleInfo): - Specifies the vehicle information. - toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): - Encapsulates information about toll passes. If toll passes - are provided, the API tries to return the pass price. If - toll passes are not provided, the API treats the toll pass - as unknown and tries to return the cash price. Applies only - to the DRIVE and TWO_WHEELER travel modes. - """ - - avoid_tolls: bool = proto.Field( - proto.BOOL, - number=1, - ) - avoid_highways: bool = proto.Field( - proto.BOOL, - number=2, - ) - avoid_ferries: bool = proto.Field( - proto.BOOL, - number=3, - ) - avoid_indoor: bool = proto.Field( - proto.BOOL, - number=4, - ) - vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_vehicle_info.VehicleInfo, - ) - toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( - proto.ENUM, - number=6, - enum=gmr_toll_passes.TollPass, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py deleted file mode 100644 index 14d466006fae..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteTravelMode', - }, -) - - -class RouteTravelMode(proto.Enum): - r"""A set of values used to specify the mode of travel. NOTE: WALK, - BICYCLE, and TWO_WHEELER routes are in beta and might sometimes be - missing clear sidewalks, pedestrian paths, or bicycling paths. You - must display this warning to the user for all walking, bicycling, - and two-wheel routes that you display in your app. - - Values: - TRAVEL_MODE_UNSPECIFIED (0): - No travel mode specified. Defaults to ``DRIVE``. - DRIVE (1): - Travel by passenger car. - BICYCLE (2): - Travel by bicycle. - WALK (3): - Travel by walking. - TWO_WHEELER (4): - Two-wheeled, motorized vehicle. For example, motorcycle. - Note that this differs from the ``BICYCLE`` travel mode - which covers human-powered mode. - """ - TRAVEL_MODE_UNSPECIFIED = 0 - DRIVE = 1 - BICYCLE = 2 - WALK = 3 - TWO_WHEELER = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py deleted file mode 100644 index 12bb47231932..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py +++ /dev/null @@ -1,510 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import fallback_info as gmr_fallback_info -from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routing_preference as gmr_routing_preference -from google.maps.routing_v2.types import units as gmr_units -from google.maps.routing_v2.types import waypoint as gmr_waypoint -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteMatrixElementCondition', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'ComputeRouteMatrixRequest', - 'RouteMatrixOrigin', - 'RouteMatrixDestination', - 'RouteMatrixElement', - }, -) - - -class RouteMatrixElementCondition(proto.Enum): - r"""The condition of the route being returned. - - Values: - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): - Only used when the ``status`` of the element is not OK. - ROUTE_EXISTS (1): - A route was found, and the corresponding - information was filled out for the element. - ROUTE_NOT_FOUND (2): - No route could be found. Fields containing route - information, such as ``distance_meters`` or ``duration``, - will not be filled out in the element. - """ - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 - ROUTE_EXISTS = 1 - ROUTE_NOT_FOUND = 2 - - -class ComputeRoutesRequest(proto.Message): - r"""ComputeRoutes request message. - - Attributes: - origin (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint. - destination (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint. - intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): - Optional. A set of waypoints along the route - (excluding terminal points), for either stopping - at or passing by. Up to 25 intermediate - waypoints are supported. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, then an error is returned. You can - specify this option only when the ``travel_mode`` is - ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. - polyline_quality (google.maps.routing_v2.types.PolylineQuality): - Optional. Specifies your preference for the - quality of the polyline. - polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): - Optional. Specifies the preferred encoding - for the polyline. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't - set this value, then this value defaults to the - time that you made the request. If you set this - value to a time that has already occurred, then - the request fails. - compute_alternative_routes (bool): - Optional. Specifies whether to calculate - alternate routes in addition to the route. - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. A set of conditions to satisfy that - affect the way routes are calculated. - language_code (str): - Optional. The BCP-47 language code, such as "en-US" or - "sr-Latn". For more information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - See `Language - Support `__ - for the list of supported languages. When you don't provide - this value, the display language is inferred from the - location of the route request. - units (google.maps.routing_v2.types.Units): - Optional. Specifies the units of measure for the display - fields. This includes the ``instruction`` field in - ``NavigationInstruction``. The units of measure used for the - route, leg, step distance, and duration are not affected by - this value. If you don't provide this value, then the - display units are inferred from the location of the request. - requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): - Optional. Specifies what reference routes to calculate as - part of the request in addition to the default route. A - reference route is a route with a different route - calculation objective than the default route. For example an - FUEL_EFFICIENT reference route calculation takes into - account various parameters that would generate an optimal - fuel efficient route. - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - """ - class ReferenceRoute(proto.Enum): - r"""A supported reference route on the ComputeRoutesRequest. - - Values: - REFERENCE_ROUTE_UNSPECIFIED (0): - Not used. Requests containing this value - fail. - FUEL_EFFICIENT (1): - Fuel efficient route. Routes labeled with - this value are determined to be optimized for - parameters such as fuel consumption. - """ - REFERENCE_ROUTE_UNSPECIFIED = 0 - FUEL_EFFICIENT = 1 - - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the route(s). - FUEL_CONSUMPTION (2): - Estimated fuel consumption for the route(s). - TRAFFIC_ON_POLYLINE (3): - Traffic aware polylines for the route(s). - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - FUEL_CONSUMPTION = 2 - TRAFFIC_ON_POLYLINE = 3 - - origin: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - destination: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_waypoint.Waypoint, - ) - intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=gmr_waypoint.Waypoint, - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=4, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=5, - enum=gmr_routing_preference.RoutingPreference, - ) - polyline_quality: polyline.PolylineQuality = proto.Field( - proto.ENUM, - number=6, - enum=polyline.PolylineQuality, - ) - polyline_encoding: polyline.PolylineEncoding = proto.Field( - proto.ENUM, - number=12, - enum=polyline.PolylineEncoding, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - compute_alternative_routes: bool = proto.Field( - proto.BOOL, - number=8, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=9, - message=gmr_route_modifiers.RouteModifiers, - ) - language_code: str = proto.Field( - proto.STRING, - number=10, - ) - units: gmr_units.Units = proto.Field( - proto.ENUM, - number=11, - enum=gmr_units.Units, - ) - requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( - proto.ENUM, - number=14, - enum=ReferenceRoute, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=15, - enum=ExtraComputation, - ) - - -class ComputeRoutesResponse(proto.Message): - r"""ComputeRoutes the response message. - - Attributes: - routes (MutableSequence[google.maps.routing_v2.types.Route]): - Contains an array of computed routes (up to three) when you - specify compute_alternatives_routes, and contains just one - route when you don't. When this array contains multiple - entries, the first one is the most recommended route. If the - array is empty, then it means no route could be found. - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route results with all of the input - preferences, it may fallback to using a - different way of computation. When fallback mode - is used, this field contains detailed info about - the fallback response. Otherwise this field is - unset. - geocoding_results (google.maps.routing_v2.types.GeocodingResults): - Contains geocoding response info for - waypoints specified as addresses. - """ - - routes: MutableSequence[route.Route] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=route.Route, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_fallback_info.FallbackInfo, - ) - geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_geocoding_results.GeocodingResults, - ) - - -class ComputeRouteMatrixRequest(proto.Message): - r"""ComputeRouteMatrix request message - - Attributes: - origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): - Required. Array of origins, which determines the rows of the - response matrix. Several size restrictions apply to the - cardinality of origins and destinations: - - - The number of elements (origins × destinations) must be - no greater than 625 in any case. - - The number of elements (origins × destinations) must be - no greater than 100 if routing_preference is set to - ``TRAFFIC_AWARE_OPTIMAL``. - - The number of waypoints (origins + destinations) - specified as ``place_id`` must be no greater than 50. - destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): - Required. Array of destinations, which - determines the columns of the response matrix. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, an error is returned. You can specify - this option only when the ``travel_mode`` is ``DRIVE`` or - ``TWO_WHEELER``, otherwise the request fails. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't - set this value, this defaults to the time that - you made the request. If you set this value to a - time that has already occurred, the request - fails. - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - """ - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the matrix element(s). - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - - origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteMatrixOrigin', - ) - destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='RouteMatrixDestination', - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=3, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=4, - enum=gmr_routing_preference.RoutingPreference, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=8, - enum=ExtraComputation, - ) - - -class RouteMatrixOrigin(proto.Message): - r"""A single origin for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. Modifiers for every route that - takes this as the origin - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_route_modifiers.RouteModifiers, - ) - - -class RouteMatrixDestination(proto.Message): - r"""A single destination for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - - -class RouteMatrixElement(proto.Message): - r"""Encapsulates route information computed for an - origin/destination pair in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - origin_index (int): - Zero-based index of the origin in the - request. - - This field is a member of `oneof`_ ``_origin_index``. - destination_index (int): - Zero-based index of the destination in the - request. - - This field is a member of `oneof`_ ``_destination_index``. - status (google.rpc.status_pb2.Status): - Error status code for this element. - condition (google.maps.routing_v2.types.RouteMatrixElementCondition): - Indicates whether the route was found or not. - Independent of status. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the route - without taking traffic conditions into - consideration. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. For - example: restriction information and toll - information - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route with the given preferences for - this particular origin/destination pair, it may - fall back to using a different mode of - computation. When fallback mode is used, this - field contains detailed information about the - fallback response. Otherwise this field is - unset. - """ - - origin_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - destination_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - condition: 'RouteMatrixElementCondition' = proto.Field( - proto.ENUM, - number=9, - enum='RouteMatrixElementCondition', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=4, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - travel_advisory: route.RouteTravelAdvisory = proto.Field( - proto.MESSAGE, - number=7, - message=route.RouteTravelAdvisory, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=8, - message=gmr_fallback_info.FallbackInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py deleted file mode 100644 index d7d3a75786b1..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RoutingPreference', - }, -) - - -class RoutingPreference(proto.Enum): - r"""A set of values that specify factors to take into - consideration when calculating the route. - - Values: - ROUTING_PREFERENCE_UNSPECIFIED (0): - No routing preference specified. Default to - ``TRAFFIC_UNAWARE``. - TRAFFIC_UNAWARE (1): - Computes routes without taking live traffic conditions into - consideration. Suitable when traffic conditions don't matter - or are not applicable. Using this value produces the lowest - latency. Note: For ``RouteTravelMode`` DRIVE and TWO_WHEELER - choice of route and duration are based on road network and - average time-independent traffic conditions. Results for a - given request may vary over time due to changes in the road - network, updated average traffic conditions, and the - distributed nature of the service. Results may also vary - between nearly-equivalent routes at any time or frequency. - TRAFFIC_AWARE (2): - Calculates routes taking live traffic conditions into - consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, - some optimizations are applied to significantly reduce - latency. - TRAFFIC_AWARE_OPTIMAL (3): - Calculates the routes taking live traffic - conditions into consideration, without applying - most performance optimizations. Using this value - produces the highest latency. - """ - ROUTING_PREFERENCE_UNSPECIFIED = 0 - TRAFFIC_UNAWARE = 1 - TRAFFIC_AWARE = 2 - TRAFFIC_AWARE_OPTIMAL = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py deleted file mode 100644 index 9a322fff1e94..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'SpeedReadingInterval', - }, -) - - -class SpeedReadingInterval(proto.Message): - r"""Traffic density indicator on a contiguous segment of a polyline or - path. Given a path with points P_0, P_1, ... , P_N (zero-based - index), the SpeedReadingInterval defines an interval and describes - its traffic using the following categories. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - start_polyline_point_index (int): - The starting index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_start_polyline_point_index``. - end_polyline_point_index (int): - The ending index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_end_polyline_point_index``. - speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): - Traffic speed in this interval. - """ - class Speed(proto.Enum): - r"""The classification of polyline speed based on traffic data. - - Values: - SPEED_UNSPECIFIED (0): - Default value. This value is unused. - NORMAL (1): - Normal speed, no slowdown is detected. - SLOW (2): - Slowdown detected, but no traffic jam formed. - TRAFFIC_JAM (3): - Traffic jam detected. - """ - SPEED_UNSPECIFIED = 0 - NORMAL = 1 - SLOW = 2 - TRAFFIC_JAM = 3 - - start_polyline_point_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - end_polyline_point_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - speed: Speed = proto.Field( - proto.ENUM, - number=3, - enum=Speed, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py deleted file mode 100644 index 3182bd03ac01..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.type import money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TollInfo', - }, -) - - -class TollInfo(proto.Message): - r"""Encapsulates toll information on a ``Route`` or on a ``RouteLeg``. - - Attributes: - estimated_price (MutableSequence[google.type.money_pb2.Money]): - The monetary amount of tolls for the - corresponding Route or RouteLeg. This list - contains a money amount for each currency that - is expected to be charged by the toll stations. - Typically this list will contain only one item - for routes with tolls in one currency. For - international trips, this list may contain - multiple items to reflect tolls in different - currencies. - """ - - estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=money_pb2.Money, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py deleted file mode 100644 index 05edb1a082c3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py +++ /dev/null @@ -1,348 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TollPass', - }, -) - - -class TollPass(proto.Enum): - r"""List of toll passes around the world that we support. - - Values: - TOLL_PASS_UNSPECIFIED (0): - Not used. If this value is used, then the - request fails. - AU_ETOLL_TAG (82): - Sydney toll pass. See additional details at - https://www.myetoll.com.au. - AU_EWAY_TAG (83): - Sydney toll pass. See additional details at - https://www.tollpay.com.au. - AU_LINKT (2): - Australia-wide toll pass. - See additional details at - https://www.linkt.com.au/. - AR_TELEPASE (3): - Argentina toll pass. See additional details - at https://telepase.com.ar - BR_AUTO_EXPRESO (81): - Brazil toll pass. See additional details at - https://www.autoexpreso.com - BR_CONECTCAR (7): - Brazil toll pass. See additional details at - https://conectcar.com. - BR_MOVE_MAIS (8): - Brazil toll pass. See additional details at - https://movemais.com. - BR_PASSA_RAPIDO (88): - Brazil toll pass. See additional details at - https://pasorapido.gob.do/ - BR_SEM_PARAR (9): - Brazil toll pass. See additional details at - https://www.semparar.com.br. - BR_TAGGY (10): - Brazil toll pass. See additional details at - https://taggy.com.br. - BR_VELOE (11): - Brazil toll pass. See additional details at - https://veloe.com.br/site/onde-usar. - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): - Canada to United States border crossing. - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): - Canada to United States border crossing. - CA_US_BLUE_WATER_EDGE_PASS (18): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_CONNEXION (19): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_NEXUS_CARD (20): - Canada to United States border crossing. - ID_E_TOLL (16): - Indonesia. - E-card provided by multiple banks used to pay - for tolls. All e-cards via banks are charged the - same so only one enum value is needed. E.g. - - Bank Mandiri - https://www.bankmandiri.co.id/e-money - BCA - https://www.bca.co.id/flazz - - BNI - https://www.bni.co.id/id-id/ebanking/tapcash - IN_FASTAG (78): - India. - IN_LOCAL_HP_PLATE_EXEMPT (79): - India, HP state plate exemption. - MX_IAVE (90): - Mexico toll pass. - https://iave.capufe.gob.mx/#/ - MX_PASE (91): - Mexico - https://www.pase.com.mx - MX_QUICKPASS (93): - Mexico - https://operadoravial.com/quick-pass/ - MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): - http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf - MX_TAG_IAVE (12): - Mexico - MX_TAG_TELEVIA (13): - Mexico toll pass company. One of many - operating in Mexico City. See additional details - at https://www.televia.com.mx. - MX_TELEVIA (92): - Mexico toll pass company. One of many - operating in Mexico City. - https://www.televia.com.mx - MX_VIAPASS (14): - Mexico toll pass. See additional details at - https://www.viapass.com.mx/viapass/web_home.aspx. - US_AL_FREEDOM_PASS (21): - AL, USA. - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): - AK, USA. - US_CA_FASTRAK (4): - CA, USA. - US_CA_FASTRAK_CAV_STICKER (86): - Indicates driver has any FasTrak pass in - addition to the DMV issued Clean Air Vehicle - (CAV) sticker. - https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml - US_CO_EXPRESSTOLL (23): - CO, USA. - US_CO_GO_PASS (24): - CO, USA. - US_DE_EZPASSDE (25): - DE, USA. - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): - FL, USA. - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): - FL, USA. - US_FL_EPASS (67): - FL, USA. - US_FL_GIBA_TOLL_PASS (68): - FL, USA. - US_FL_LEEWAY (69): - FL, USA. - US_FL_SUNPASS (70): - FL, USA. - US_FL_SUNPASS_PRO (71): - FL, USA. - US_IL_EZPASSIL (73): - IL, USA. - US_IL_IPASS (72): - IL, USA. - US_IN_EZPASSIN (26): - IN, USA. - US_KS_BESTPASS_HORIZON (27): - KS, USA. - US_KS_KTAG (28): - KS, USA. - US_KS_NATIONALPASS (29): - KS, USA. - US_KS_PREPASS_ELITEPASS (30): - KS, USA. - US_KY_RIVERLINK (31): - KY, USA. - US_LA_GEAUXPASS (32): - LA, USA. - US_LA_TOLL_TAG (33): - LA, USA. - US_MA_EZPASSMA (6): - MA, USA. - US_MD_EZPASSMD (34): - MD, USA. - US_ME_EZPASSME (35): - ME, USA. - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): - MI, USA. - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): - MI, USA. - US_MI_IQ_PROX_CARD (38): - MI, USA. - US_MI_MACKINAC_BRIDGE_MAC_PASS (39): - MI, USA. - US_MI_NEXPRESS_TOLL (40): - MI, USA. - US_MN_EZPASSMN (41): - MN, USA. - US_NC_EZPASSNC (42): - NC, USA. - US_NC_PEACH_PASS (87): - NC, USA. - US_NC_QUICK_PASS (43): - NC, USA. - US_NH_EZPASSNH (80): - NH, USA. - US_NJ_DOWNBEACH_EXPRESS_PASS (75): - NJ, USA. - US_NJ_EZPASSNJ (74): - NJ, USA. - US_NY_EXPRESSPASS (76): - NY, USA. - US_NY_EZPASSNY (77): - NY, USA. - US_OH_EZPASSOH (44): - OH, USA. - US_PA_EZPASSPA (45): - PA, USA. - US_RI_EZPASSRI (46): - RI, USA. - US_SC_PALPASS (47): - SC, USA. - US_TX_BANCPASS (48): - TX, USA. - US_TX_DEL_RIO_PASS (49): - TX, USA. - US_TX_EFAST_PASS (50): - TX, USA. - US_TX_EAGLE_PASS_EXPRESS_CARD (51): - TX, USA. - US_TX_EPTOLL (52): - TX, USA. - US_TX_EZ_CROSS (53): - TX, USA. - US_TX_EZTAG (54): - TX, USA. - US_TX_LAREDO_TRADE_TAG (55): - TX, USA. - US_TX_PLUSPASS (56): - TX, USA. - US_TX_TOLLTAG (57): - TX, USA. - US_TX_TXTAG (58): - TX, USA. - US_TX_XPRESS_CARD (59): - TX, USA. - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): - UT, USA. - US_VA_EZPASSVA (61): - VA, USA. - US_WA_BREEZEBY (17): - WA, USA. - US_WA_GOOD_TO_GO (1): - WA, USA. - US_WV_EZPASSWV (62): - WV, USA. - US_WV_MEMORIAL_BRIDGE_TICKETS (63): - WV, USA. - US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): - WV, USA. - """ - TOLL_PASS_UNSPECIFIED = 0 - AU_ETOLL_TAG = 82 - AU_EWAY_TAG = 83 - AU_LINKT = 2 - AR_TELEPASE = 3 - BR_AUTO_EXPRESO = 81 - BR_CONECTCAR = 7 - BR_MOVE_MAIS = 8 - BR_PASSA_RAPIDO = 88 - BR_SEM_PARAR = 9 - BR_TAGGY = 10 - BR_VELOE = 11 - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 - CA_US_BLUE_WATER_EDGE_PASS = 18 - CA_US_CONNEXION = 19 - CA_US_NEXUS_CARD = 20 - ID_E_TOLL = 16 - IN_FASTAG = 78 - IN_LOCAL_HP_PLATE_EXEMPT = 79 - MX_IAVE = 90 - MX_PASE = 91 - MX_QUICKPASS = 93 - MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 - MX_TAG_IAVE = 12 - MX_TAG_TELEVIA = 13 - MX_TELEVIA = 92 - MX_VIAPASS = 14 - US_AL_FREEDOM_PASS = 21 - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 - US_CA_FASTRAK = 4 - US_CA_FASTRAK_CAV_STICKER = 86 - US_CO_EXPRESSTOLL = 23 - US_CO_GO_PASS = 24 - US_DE_EZPASSDE = 25 - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 - US_FL_EPASS = 67 - US_FL_GIBA_TOLL_PASS = 68 - US_FL_LEEWAY = 69 - US_FL_SUNPASS = 70 - US_FL_SUNPASS_PRO = 71 - US_IL_EZPASSIL = 73 - US_IL_IPASS = 72 - US_IN_EZPASSIN = 26 - US_KS_BESTPASS_HORIZON = 27 - US_KS_KTAG = 28 - US_KS_NATIONALPASS = 29 - US_KS_PREPASS_ELITEPASS = 30 - US_KY_RIVERLINK = 31 - US_LA_GEAUXPASS = 32 - US_LA_TOLL_TAG = 33 - US_MA_EZPASSMA = 6 - US_MD_EZPASSMD = 34 - US_ME_EZPASSME = 35 - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 - US_MI_IQ_PROX_CARD = 38 - US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 - US_MI_NEXPRESS_TOLL = 40 - US_MN_EZPASSMN = 41 - US_NC_EZPASSNC = 42 - US_NC_PEACH_PASS = 87 - US_NC_QUICK_PASS = 43 - US_NH_EZPASSNH = 80 - US_NJ_DOWNBEACH_EXPRESS_PASS = 75 - US_NJ_EZPASSNJ = 74 - US_NY_EXPRESSPASS = 76 - US_NY_EZPASSNY = 77 - US_OH_EZPASSOH = 44 - US_PA_EZPASSPA = 45 - US_RI_EZPASSRI = 46 - US_SC_PALPASS = 47 - US_TX_BANCPASS = 48 - US_TX_DEL_RIO_PASS = 49 - US_TX_EFAST_PASS = 50 - US_TX_EAGLE_PASS_EXPRESS_CARD = 51 - US_TX_EPTOLL = 52 - US_TX_EZ_CROSS = 53 - US_TX_EZTAG = 54 - US_TX_LAREDO_TRADE_TAG = 55 - US_TX_PLUSPASS = 56 - US_TX_TOLLTAG = 57 - US_TX_TXTAG = 58 - US_TX_XPRESS_CARD = 59 - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 - US_VA_EZPASSVA = 61 - US_WA_BREEZEBY = 17 - US_WA_GOOD_TO_GO = 1 - US_WV_EZPASSWV = 62 - US_WV_MEMORIAL_BRIDGE_TICKETS = 63 - US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py deleted file mode 100644 index 93cfaf1ee04c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Units', - }, -) - - -class Units(proto.Enum): - r"""A set of values that specify the unit of measure used in the - display. - - Values: - UNITS_UNSPECIFIED (0): - Units of measure not specified. Defaults to - the unit of measure inferred from the request. - METRIC (1): - Metric units of measure. - IMPERIAL (2): - Imperial (English) units of measure. - """ - UNITS_UNSPECIFIED = 0 - METRIC = 1 - IMPERIAL = 2 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py deleted file mode 100644 index a94a99025c80..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'VehicleEmissionType', - }, -) - - -class VehicleEmissionType(proto.Enum): - r"""A set of values describing the vehicle's emission type. - Applies only to the DRIVE travel mode. - - Values: - VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): - No emission type specified. Default to - GASOLINE. - GASOLINE (1): - Gasoline/petrol fueled vehicle. - ELECTRIC (2): - Electricity powered vehicle. - HYBRID (3): - Hybrid fuel (such as gasoline + electric) - vehicle. - DIESEL (4): - Diesel fueled vehicle. - """ - VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 - GASOLINE = 1 - ELECTRIC = 2 - HYBRID = 3 - DIESEL = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py deleted file mode 100644 index 2d71bb0a70a0..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import vehicle_emission_type - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'VehicleInfo', - }, -) - - -class VehicleInfo(proto.Message): - r"""Encapsulates the vehicle information, such as the license - plate last character. - - Attributes: - emission_type (google.maps.routing_v2.types.VehicleEmissionType): - Describes the vehicle's emission type. - Applies only to the DRIVE travel mode. - """ - - emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( - proto.ENUM, - number=2, - enum=vehicle_emission_type.VehicleEmissionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py deleted file mode 100644 index c25013cfd086..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import location as gmr_location - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Waypoint', - }, -) - - -class Waypoint(proto.Message): - r"""Encapsulates a waypoint. Waypoints mark both the beginning - and end of a route, and include intermediate stops along the - route. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - location (google.maps.routing_v2.types.Location): - A point specified using geographic - coordinates, including an optional heading. - - This field is a member of `oneof`_ ``location_type``. - place_id (str): - The POI Place ID associated with the - waypoint. - - This field is a member of `oneof`_ ``location_type``. - address (str): - Human readable address or a plus code. - See https://plus.codes for details. - - This field is a member of `oneof`_ ``location_type``. - via (bool): - Marks this waypoint as a milestone rather a stopping point. - For each non-via waypoint in the request, the response - appends an entry to the ``legs`` array to provide the - details for stopovers on that leg of the trip. Set this - value to true when you want the route to pass through this - waypoint without stopping over. Via waypoints don't cause an - entry to be added to the ``legs`` array, but they do route - the journey through the waypoint. You can only set this - value on waypoints that are intermediates. The request fails - if you set this field on terminal waypoints. If - ``ComputeRoutesRequest.optimize_waypoint_order`` is set to - true then this field cannot be set to true; otherwise, the - request fails. - vehicle_stopover (bool): - Indicates that the waypoint is meant for vehicles to stop - at, where the intention is to either pickup or drop-off. - When you set this value, the calculated route won't include - non-\ ``via`` waypoints on roads that are unsuitable for - pickup and drop-off. This option works only for ``DRIVE`` - and ``TWO_WHEELER`` travel modes, and when the - ``location_type`` is ``location``. - side_of_road (bool): - Indicates that the location of this waypoint is meant to - have a preference for the vehicle to stop at a particular - side of road. When you set this value, the route will pass - through the location so that the vehicle can stop at the - side of road that the location is biased towards from the - center of the road. This option works only for 'DRIVE' and - 'TWO_WHEELER' travel modes. - """ - - location: gmr_location.Location = proto.Field( - proto.MESSAGE, - number=1, - oneof='location_type', - message=gmr_location.Location, - ) - place_id: str = proto.Field( - proto.STRING, - number=2, - oneof='location_type', - ) - address: str = proto.Field( - proto.STRING, - number=7, - oneof='location_type', - ) - via: bool = proto.Field( - proto.BOOL, - number=3, - ) - vehicle_stopover: bool = proto.Field( - proto.BOOL, - number=4, - ) - side_of_road: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py deleted file mode 100644 index 59757e684c85..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/routing_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py deleted file mode 100644 index 381f53f7a26e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py deleted file mode 100644 index 125691404b0b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py deleted file mode 100644 index c978c3e55cd7..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py deleted file mode 100644 index ca13730e4ddc..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json deleted file mode 100644 index b5ed5aca319c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json +++ /dev/null @@ -1,321 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.routing.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-maps-routing", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_route_matrix_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_route_matrix_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_routes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_routes_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py deleted file mode 100644 index 291c4ea93db5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class routingCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'extra_computations', ), - 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'units', 'requested_reference_routes', 'extra_computations', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=routingCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the routing client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py deleted file mode 100644 index 1047dfef360b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-maps-routing' - - -description = "Google Maps Routing API client library" - -version = {} -with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-maps-routing" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.maps"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adfea7ee..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py deleted file mode 100644 index 55f7b3a4ba31..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py +++ /dev/null @@ -1,1750 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.maps.routing_v2.services.routes import RoutesAsyncClient -from google.maps.routing_v2.services.routes import RoutesClient -from google.maps.routing_v2.services.routes import transports -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routes_service -from google.maps.routing_v2.types import routing_preference -from google.maps.routing_v2.types import toll_passes -from google.maps.routing_v2.types import units -from google.maps.routing_v2.types import vehicle_emission_type -from google.maps.routing_v2.types import vehicle_info -from google.maps.routing_v2.types import waypoint -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -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 RoutesClient._get_default_mtls_endpoint(None) is None - assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RoutesGrpcTransport, "grpc"), - (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RoutesRestTransport, "rest"), -]) -def test_routes_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -def test_routes_client_get_transport_class(): - transport = RoutesClient.get_transport_class() - available_transports = [ - transports.RoutesGrpcTransport, - transports.RoutesRestTransport, - ] - assert transport in available_transports - - transport = RoutesClient.get_transport_class("grpc") - assert transport == transports.RoutesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -def test_routes_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RoutesClient, transports.RoutesRestTransport, "rest", "true"), - (RoutesClient, transports.RoutesRestTransport, "rest", "false"), -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_routes_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - RoutesClient, RoutesAsyncClient -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -def test_routes_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -def test_routes_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RoutesClient, transports.RoutesRestTransport, "rest", None), -]) -def test_routes_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_routes_client_client_options_from_dict(): - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RoutesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_routes_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "routes.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes(request_type, transport: str = 'grpc'): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = routes_service.ComputeRoutesResponse( - ) - response = client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - client.compute_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - -@pytest.mark.asyncio -async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( - )) - response = await client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -@pytest.mark.asyncio -async def test_compute_routes_async_from_dict(): - await test_compute_routes_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix(request_type, transport: str = 'grpc'): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([routes_service.RouteMatrixElement()]) - response = client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, routes_service.RouteMatrixElement) - - -def test_compute_route_matrix_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - client.compute_route_matrix() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - -@pytest.mark.asyncio -async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) - response = await client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, routes_service.RouteMatrixElement) - - -@pytest.mark.asyncio -async def test_compute_route_matrix_async_from_dict(): - await test_compute_route_matrix_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes_rest(request_type): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = routes_service.ComputeRoutesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.compute_routes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): - transport_class = transports.RoutesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.ComputeRoutesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.compute_routes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_routes_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_routes._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_routes_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) - - request = routes_service.ComputeRoutesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.ComputeRoutesResponse() - - client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compute_routes_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRoutesRequest): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.compute_routes(request) - - -def test_compute_routes_rest_error(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix_rest(request_type): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = routes_service.RouteMatrixElement( - origin_index=1279, - destination_index=1817, - condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, - distance_meters=1594, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - json_return_value = "[{}]".format(json_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.compute_route_matrix(request) - - assert isinstance(response, Iterable) - response = next(response) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.RouteMatrixElement) - assert response.origin_index == 1279 - assert response.destination_index == 1817 - assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS - assert response.distance_meters == 1594 - - -def test_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): - transport_class = transports.RoutesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.RouteMatrixElement() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - json_return_value = "[{}]".format(json_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.compute_route_matrix(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_route_matrix_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_route_matrix_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) - req.return_value._content = "[{}]".format(req.return_value._content) - - request = routes_service.ComputeRouteMatrixRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.RouteMatrixElement() - - client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compute_route_matrix_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.compute_route_matrix(request) - - -def test_compute_route_matrix_rest_error(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RoutesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RoutesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = RoutesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RoutesGrpcTransport, - ) - -def test_routes_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_routes_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'compute_routes', - 'compute_route_matrix', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_routes_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -def test_routes_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport() - adc.assert_called_once() - - -def test_routes_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - RoutesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - ], -) -def test_routes_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, - ], -) -def test_routes_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.RoutesGrpcTransport, grpc_helpers), - (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_routes_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "routes.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_routes_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.RoutesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_routes_host_no_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_routes_host_with_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_routes_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RoutesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RoutesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.compute_routes._session - session2 = client2.transport.compute_routes._session - assert session1 != session2 - session1 = client1.transport.compute_route_matrix._session - session2 = client2.transport.compute_route_matrix._session - assert session1 != session2 -def test_routes_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_routes_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - 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 - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - 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=cred, - credentials_file=None, - scopes=None, - 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 - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_transport_channel_mtls_with_adc( - transport_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), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - 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 - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RoutesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = RoutesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = RoutesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = RoutesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RoutesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = RoutesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = RoutesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = RoutesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RoutesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = RoutesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: - transport_class = RoutesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (RoutesClient, transports.RoutesGrpcTransport), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/packages/google-maps-routing/google/maps/routing/__init__.py b/packages/google-maps-routing/google/maps/routing/__init__.py index 3525247e0abd..ef47c5e1bb55 100644 --- a/packages/google-maps-routing/google/maps/routing/__init__.py +++ b/packages/google-maps-routing/google/maps/routing/__init__.py @@ -25,6 +25,10 @@ FallbackReason, FallbackRoutingMode, ) +from google.maps.routing_v2.types.geocoding_results import ( + GeocodedWaypoint, + GeocodingResults, +) from google.maps.routing_v2.types.location import Location from google.maps.routing_v2.types.maneuver import Maneuver from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction @@ -68,6 +72,8 @@ "FallbackInfo", "FallbackReason", "FallbackRoutingMode", + "GeocodedWaypoint", + "GeocodingResults", "Location", "Maneuver", "NavigationInstruction", diff --git a/packages/google-maps-routing/google/maps/routing_v2/__init__.py b/packages/google-maps-routing/google/maps/routing_v2/__init__.py index 7a01b221ac2e..4c3204fd4875 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/__init__.py +++ b/packages/google-maps-routing/google/maps/routing_v2/__init__.py @@ -20,6 +20,7 @@ from .services.routes import RoutesAsyncClient, RoutesClient from .types.fallback_info import FallbackInfo, FallbackReason, FallbackRoutingMode +from .types.geocoding_results import GeocodedWaypoint, GeocodingResults from .types.location import Location from .types.maneuver import Maneuver from .types.navigation_instruction import NavigationInstruction @@ -61,6 +62,8 @@ "FallbackInfo", "FallbackReason", "FallbackRoutingMode", + "GeocodedWaypoint", + "GeocodingResults", "Location", "Maneuver", "NavigationInstruction", diff --git a/packages/google-maps-routing/google/maps/routing_v2/services/routes/async_client.py b/packages/google-maps-routing/google/maps/routing_v2/services/routes/async_client.py index a026c56d4229..c27576e1df92 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/services/routes/async_client.py +++ b/packages/google-maps-routing/google/maps/routing_v2/services/routes/async_client.py @@ -47,7 +47,12 @@ from google.protobuf import duration_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore -from google.maps.routing_v2.types import fallback_info, route, routes_service +from google.maps.routing_v2.types import ( + fallback_info, + geocoding_results, + route, + routes_service, +) from .client import RoutesClient from .transports.base import DEFAULT_CLIENT_INFO, RoutesTransport diff --git a/packages/google-maps-routing/google/maps/routing_v2/services/routes/client.py b/packages/google-maps-routing/google/maps/routing_v2/services/routes/client.py index 4d19e6dd5365..8d4a09c031e3 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/services/routes/client.py +++ b/packages/google-maps-routing/google/maps/routing_v2/services/routes/client.py @@ -50,7 +50,12 @@ from google.protobuf import duration_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore -from google.maps.routing_v2.types import fallback_info, route, routes_service +from google.maps.routing_v2.types import ( + fallback_info, + geocoding_results, + route, + routes_service, +) from .transports.base import DEFAULT_CLIENT_INFO, RoutesTransport from .transports.grpc import RoutesGrpcTransport diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/__init__.py b/packages/google-maps-routing/google/maps/routing_v2/types/__init__.py index 9efaa71283c5..0fc81931dc68 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/__init__.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/__init__.py @@ -14,6 +14,7 @@ # limitations under the License. # from .fallback_info import FallbackInfo, FallbackReason, FallbackRoutingMode +from .geocoding_results import GeocodedWaypoint, GeocodingResults from .location import Location from .navigation_instruction import NavigationInstruction from .polyline import Polyline, PolylineEncoding, PolylineQuality @@ -44,6 +45,8 @@ "FallbackInfo", "FallbackReason", "FallbackRoutingMode", + "GeocodedWaypoint", + "GeocodingResults", "Location", "Maneuver", "NavigationInstruction", diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py similarity index 91% rename from owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py rename to packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py index ffa385a59a75..24a07165a904 100644 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py @@ -17,16 +17,14 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.rpc import status_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.maps.routing.v2', + package="google.maps.routing.v2", manifest={ - 'GeocodingResults', - 'GeocodedWaypoint', + "GeocodingResults", + "GeocodedWaypoint", }, ) @@ -47,20 +45,20 @@ class GeocodingResults(proto.Message): the order they were specified in the request. """ - origin: 'GeocodedWaypoint' = proto.Field( + origin: "GeocodedWaypoint" = proto.Field( proto.MESSAGE, number=1, - message='GeocodedWaypoint', + message="GeocodedWaypoint", ) - destination: 'GeocodedWaypoint' = proto.Field( + destination: "GeocodedWaypoint" = proto.Field( proto.MESSAGE, number=2, - message='GeocodedWaypoint', + message="GeocodedWaypoint", ) - intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( + intermediates: MutableSequence["GeocodedWaypoint"] = proto.RepeatedField( proto.MESSAGE, number=3, - message='GeocodedWaypoint', + message="GeocodedWaypoint", ) diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route.py b/packages/google-maps-routing/google/maps/routing_v2/types/route.py index be3622847d42..b53dbf1fc163 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route.py @@ -17,7 +17,7 @@ from typing import MutableMapping, MutableSequence -import google.geo.type.types +from google.geo.type import viewport_pb2 # type: ignore from google.protobuf import duration_pb2 # type: ignore import proto # type: ignore @@ -82,7 +82,7 @@ class Route(proto.Message): warnings (MutableSequence[str]): An array of warnings to show when displaying the route. - viewport (google.geo.type.types.Viewport): + viewport (google.geo.type.viewport_pb2.Viewport): The viewport bounding box of the polyline. travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): Additional information about the route. @@ -137,10 +137,10 @@ class Route(proto.Message): proto.STRING, number=7, ) - viewport: google.geo.type.types.Viewport = proto.Field( + viewport: viewport_pb2.Viewport = proto.Field( proto.MESSAGE, number=8, - message=google.geo.type.types.Viewport, + message=viewport_pb2.Viewport, ) travel_advisory: "RouteTravelAdvisory" = proto.Field( proto.MESSAGE, @@ -254,19 +254,7 @@ class RouteLegStepTravelAdvisory(proto.Message): Attributes: speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the RouteLegStep without - overlap. The start point of a specified interval is the same - as the end point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). + NOTE: This field is not currently populated. """ speed_reading_intervals: MutableSequence[ diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py index d6b3374333c4..36b93db88bf2 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py @@ -22,6 +22,7 @@ from google.rpc import status_pb2 # type: ignore import proto # type: ignore +from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results from google.maps.routing_v2.types import routing_preference as gmr_routing_preference from google.maps.routing_v2.types import fallback_info as gmr_fallback_info from google.maps.routing_v2.types import polyline, route @@ -259,6 +260,9 @@ class ComputeRoutesResponse(proto.Message): is used, this field contains detailed info about the fallback response. Otherwise this field is unset. + geocoding_results (google.maps.routing_v2.types.GeocodingResults): + Contains geocoding response info for + waypoints specified as addresses. """ routes: MutableSequence[route.Route] = proto.RepeatedField( @@ -271,6 +275,11 @@ class ComputeRoutesResponse(proto.Message): number=2, message=gmr_fallback_info.FallbackInfo, ) + geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_geocoding_results.GeocodingResults, + ) class ComputeRouteMatrixRequest(proto.Message): diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py b/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py index a768b3fe1cde..0b8158d4c5ff 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py @@ -51,6 +51,11 @@ class Waypoint(proto.Message): The POI Place ID associated with the waypoint. + This field is a member of `oneof`_ ``location_type``. + address (str): + Human readable address or a plus code. + See https://plus.codes for details. + This field is a member of `oneof`_ ``location_type``. via (bool): Marks this waypoint as a milestone rather a stopping point. @@ -95,6 +100,11 @@ class Waypoint(proto.Message): number=2, oneof="location_type", ) + address: str = proto.Field( + proto.STRING, + number=7, + oneof="location_type", + ) via: bool = proto.Field( proto.BOOL, number=3, diff --git a/packages/google-maps-routing/setup.py b/packages/google-maps-routing/setup.py index 9baa2a95020c..bedb432b4c3a 100644 --- a/packages/google-maps-routing/setup.py +++ b/packages/google-maps-routing/setup.py @@ -40,7 +40,6 @@ "proto-plus >= 1.22.0, <2.0.0dev", "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "google-geo-type<1.0.0dev", ] url = "https://github.com/googleapis/google-cloud-python" diff --git a/packages/google-maps-routing/testing/constraints-3.7.txt b/packages/google-maps-routing/testing/constraints-3.7.txt index 33ac865954a6..6c44adfea7ee 100644 --- a/packages/google-maps-routing/testing/constraints-3.7.txt +++ b/packages/google-maps-routing/testing/constraints-3.7.txt @@ -7,4 +7,3 @@ google-api-core==1.34.0 proto-plus==1.22.0 protobuf==3.19.5 -google-geo-type==0.1.0 diff --git a/packages/google-maps-routing/tests/unit/gapic/routing_v2/test_routes.py b/packages/google-maps-routing/tests/unit/gapic/routing_v2/test_routes.py index d55a16fe2d67..068ec592948f 100644 --- a/packages/google-maps-routing/tests/unit/gapic/routing_v2/test_routes.py +++ b/packages/google-maps-routing/tests/unit/gapic/routing_v2/test_routes.py @@ -54,6 +54,7 @@ ) from google.maps.routing_v2.types import ( fallback_info, + geocoding_results, location, polyline, route, From 598954648a0fe8808b71f9dbe91dad9178458540 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 10 Mar 2023 20:49:06 +0000 Subject: [PATCH 03/12] docs: clarify usage of compute_alternative_routes in proto comment PiperOrigin-RevId: 515674220 Source-Link: https://github.com/googleapis/googleapis/commit/5d7f87c599e5701039ccb94a088d762d24892781 Source-Link: https://github.com/googleapis/googleapis-gen/commit/7fe81723ec98eb6fc0c7e01188d52776533777be Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcm91dGluZy8uT3dsQm90LnlhbWwiLCJoIjoiN2ZlODE3MjNlYzk4ZWI2ZmMwYzdlMDExODhkNTI3NzY1MzM3NzdiZSJ9 --- .../google-maps-routing/v2/.coveragerc | 13 + .../google-maps-routing/v2/.flake8 | 33 + .../google-maps-routing/v2/MANIFEST.in | 2 + .../google-maps-routing/v2/README.rst | 49 + .../google-maps-routing/v2/docs/conf.py | 376 ++++ .../google-maps-routing/v2/docs/index.rst | 7 + .../v2/docs/routing_v2/routes.rst | 6 + .../v2/docs/routing_v2/services.rst | 6 + .../v2/docs/routing_v2/types.rst | 6 + .../v2/google/maps/routing/__init__.py | 97 + .../v2/google/maps/routing/gapic_version.py | 16 + .../v2/google/maps/routing/py.typed | 2 + .../v2/google/maps/routing_v2/__init__.py | 98 + .../maps/routing_v2/gapic_metadata.json | 58 + .../google/maps/routing_v2/gapic_version.py | 16 + .../v2/google/maps/routing_v2/py.typed | 2 + .../maps/routing_v2/services/__init__.py | 15 + .../routing_v2/services/routes/__init__.py | 22 + .../services/routes/async_client.py | 416 ++++ .../maps/routing_v2/services/routes/client.py | 613 ++++++ .../services/routes/transports/__init__.py | 38 + .../services/routes/transports/base.py | 161 ++ .../services/routes/transports/grpc.py | 363 ++++ .../routes/transports/grpc_asyncio.py | 362 ++++ .../services/routes/transports/rest.py | 417 ++++ .../google/maps/routing_v2/types/__init__.py | 105 + .../maps/routing_v2/types/fallback_info.py | 103 + .../routing_v2/types/geocoding_results.py | 125 ++ .../google/maps/routing_v2/types/location.py | 62 + .../google/maps/routing_v2/types/maneuver.py | 96 + .../types/navigation_instruction.py | 58 + .../google/maps/routing_v2/types/polyline.py | 113 ++ .../v2/google/maps/routing_v2/types/route.py | 409 ++++ .../maps/routing_v2/types/route_label.py | 57 + .../maps/routing_v2/types/route_modifiers.py | 97 + .../routing_v2/types/route_travel_mode.py | 59 + .../maps/routing_v2/types/routes_service.py | 512 +++++ .../routing_v2/types/routing_preference.py | 67 + .../types/speed_reading_interval.py | 89 + .../google/maps/routing_v2/types/toll_info.py | 56 + .../maps/routing_v2/types/toll_passes.py | 348 ++++ .../v2/google/maps/routing_v2/types/units.py | 49 + .../routing_v2/types/vehicle_emission_type.py | 56 + .../maps/routing_v2/types/vehicle_info.py | 50 + .../google/maps/routing_v2/types/waypoint.py | 123 ++ .../google-maps-routing/v2/mypy.ini | 3 + .../google-maps-routing/v2/noxfile.py | 184 ++ ...rated_routes_compute_route_matrix_async.py | 52 + ...erated_routes_compute_route_matrix_sync.py | 52 + ...2_generated_routes_compute_routes_async.py | 51 + ...v2_generated_routes_compute_routes_sync.py | 51 + ...ippet_metadata_google.maps.routing.v2.json | 321 +++ .../v2/scripts/fixup_routing_v2_keywords.py | 177 ++ .../google-maps-routing/v2/setup.py | 90 + .../v2/testing/constraints-3.10.txt | 6 + .../v2/testing/constraints-3.11.txt | 6 + .../v2/testing/constraints-3.12.txt | 6 + .../v2/testing/constraints-3.7.txt | 9 + .../v2/testing/constraints-3.8.txt | 6 + .../v2/testing/constraints-3.9.txt | 6 + .../google-maps-routing/v2/tests/__init__.py | 16 + .../v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/routing_v2/__init__.py | 16 + .../unit/gapic/routing_v2/test_routes.py | 1750 +++++++++++++++++ 65 files changed, 8662 insertions(+) create mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc create mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 create mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py create mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini create mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json create mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py create mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py diff --git a/owl-bot-staging/google-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc new file mode 100644 index 000000000000..d0ce5597b0a9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/routing/__init__.py + google/maps/routing/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.flake8 @@ -0,0 +1,33 @@ +# -*- 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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in new file mode 100644 index 000000000000..c5b56c111c00 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/routing *.py +recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst new file mode 100644 index 000000000000..f0002366e552 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Routing API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Maps Routing API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py new file mode 100644 index 000000000000..d7a10abed96b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-maps-routing documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +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"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-maps-routing" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# 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"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# 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 + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +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 = { + "description": "Google Maps Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# 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 + +# 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 + +# 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, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# 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 = [] + +# 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' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is 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 = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# 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' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# 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' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-maps-routing-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- 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', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-maps-routing.tex", + u"google-maps-routing 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 + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# 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 = [ + ( + root_doc, + "google-maps-routing", + u"Google Maps Routing Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-maps-routing", + u"google-maps-routing Documentation", + author, + "google-maps-routing", + "GAPIC library for Google Maps Routing API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# 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), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst new file mode 100644 index 000000000000..e2563dd88ee9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + routing_v2/services + routing_v2/types diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst new file mode 100644 index 000000000000..3d52309cddae --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst @@ -0,0 +1,6 @@ +Routes +------------------------ + +.. automodule:: google.maps.routing_v2.services.routes + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst new file mode 100644 index 000000000000..e96568dc434c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst @@ -0,0 +1,6 @@ +Services for Google Maps Routing v2 API +======================================= +.. toctree:: + :maxdepth: 2 + + routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst new file mode 100644 index 000000000000..176a5a812cf8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst @@ -0,0 +1,6 @@ +Types for Google Maps Routing v2 API +==================================== + +.. automodule:: google.maps.routing_v2.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py new file mode 100644 index 000000000000..59020a3484c3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.maps.routing import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.routing_v2.services.routes.client import RoutesClient +from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient + +from google.maps.routing_v2.types.fallback_info import FallbackInfo +from google.maps.routing_v2.types.fallback_info import FallbackReason +from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode +from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint +from google.maps.routing_v2.types.geocoding_results import GeocodingResults +from google.maps.routing_v2.types.location import Location +from google.maps.routing_v2.types.maneuver import Maneuver +from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction +from google.maps.routing_v2.types.polyline import Polyline +from google.maps.routing_v2.types.polyline import PolylineEncoding +from google.maps.routing_v2.types.polyline import PolylineQuality +from google.maps.routing_v2.types.route import Route +from google.maps.routing_v2.types.route import RouteLeg +from google.maps.routing_v2.types.route import RouteLegStep +from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory +from google.maps.routing_v2.types.route import RouteLegTravelAdvisory +from google.maps.routing_v2.types.route import RouteTravelAdvisory +from google.maps.routing_v2.types.route_label import RouteLabel +from google.maps.routing_v2.types.route_modifiers import RouteModifiers +from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode +from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse +from google.maps.routing_v2.types.routes_service import RouteMatrixDestination +from google.maps.routing_v2.types.routes_service import RouteMatrixElement +from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin +from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition +from google.maps.routing_v2.types.routing_preference import RoutingPreference +from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval +from google.maps.routing_v2.types.toll_info import TollInfo +from google.maps.routing_v2.types.toll_passes import TollPass +from google.maps.routing_v2.types.units import Units +from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType +from google.maps.routing_v2.types.vehicle_info import VehicleInfo +from google.maps.routing_v2.types.waypoint import Waypoint + +__all__ = ('RoutesClient', + 'RoutesAsyncClient', + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py new file mode 100644 index 000000000000..405b1cebcf15 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py new file mode 100644 index 000000000000..cd9d694f63c6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.maps.routing_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.routes import RoutesClient +from .services.routes import RoutesAsyncClient + +from .types.fallback_info import FallbackInfo +from .types.fallback_info import FallbackReason +from .types.fallback_info import FallbackRoutingMode +from .types.geocoding_results import GeocodedWaypoint +from .types.geocoding_results import GeocodingResults +from .types.location import Location +from .types.maneuver import Maneuver +from .types.navigation_instruction import NavigationInstruction +from .types.polyline import Polyline +from .types.polyline import PolylineEncoding +from .types.polyline import PolylineQuality +from .types.route import Route +from .types.route import RouteLeg +from .types.route import RouteLegStep +from .types.route import RouteLegStepTravelAdvisory +from .types.route import RouteLegTravelAdvisory +from .types.route import RouteTravelAdvisory +from .types.route_label import RouteLabel +from .types.route_modifiers import RouteModifiers +from .types.route_travel_mode import RouteTravelMode +from .types.routes_service import ComputeRouteMatrixRequest +from .types.routes_service import ComputeRoutesRequest +from .types.routes_service import ComputeRoutesResponse +from .types.routes_service import RouteMatrixDestination +from .types.routes_service import RouteMatrixElement +from .types.routes_service import RouteMatrixOrigin +from .types.routes_service import RouteMatrixElementCondition +from .types.routing_preference import RoutingPreference +from .types.speed_reading_interval import SpeedReadingInterval +from .types.toll_info import TollInfo +from .types.toll_passes import TollPass +from .types.units import Units +from .types.vehicle_emission_type import VehicleEmissionType +from .types.vehicle_info import VehicleInfo +from .types.waypoint import Waypoint + +__all__ = ( + 'RoutesAsyncClient', +'ComputeRouteMatrixRequest', +'ComputeRoutesRequest', +'ComputeRoutesResponse', +'FallbackInfo', +'FallbackReason', +'FallbackRoutingMode', +'GeocodedWaypoint', +'GeocodingResults', +'Location', +'Maneuver', +'NavigationInstruction', +'Polyline', +'PolylineEncoding', +'PolylineQuality', +'Route', +'RouteLabel', +'RouteLeg', +'RouteLegStep', +'RouteLegStepTravelAdvisory', +'RouteLegTravelAdvisory', +'RouteMatrixDestination', +'RouteMatrixElement', +'RouteMatrixElementCondition', +'RouteMatrixOrigin', +'RouteModifiers', +'RouteTravelAdvisory', +'RouteTravelMode', +'RoutesClient', +'RoutingPreference', +'SpeedReadingInterval', +'TollInfo', +'TollPass', +'Units', +'VehicleEmissionType', +'VehicleInfo', +'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json new file mode 100644 index 000000000000..8382cea1d39a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json @@ -0,0 +1,58 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.routing_v2", + "protoPackage": "google.maps.routing.v2", + "schema": "1.0", + "services": { + "Routes": { + "clients": { + "grpc": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RoutesAsyncClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "rest": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py new file mode 100644 index 000000000000..405b1cebcf15 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py new file mode 100644 index 000000000000..e8e1c3845db5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py new file mode 100644 index 000000000000..ff3f8f71863f --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RoutesClient +from .async_client import RoutesAsyncClient + +__all__ = ( + 'RoutesClient', + 'RoutesAsyncClient', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py new file mode 100644 index 000000000000..7f8df74a140b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union + +from google.maps.routing_v2 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .client import RoutesClient + + +class RoutesAsyncClient: + """The Routes API.""" + + _client: RoutesClient + + DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RoutesClient.common_folder_path) + parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) + common_organization_path = staticmethod(RoutesClient.common_organization_path) + parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) + common_project_path = staticmethod(RoutesClient.common_project_path) + parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) + common_location_path = staticmethod(RoutesClient.common_location_path) + parse_common_location_path = staticmethod(RoutesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(RoutesClient).get_transport_class, type(RoutesClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RoutesTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RoutesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RoutesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # Create or coerce a protobuf request object. + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compute_routes, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + # Create or coerce a protobuf request object. + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compute_route_matrix, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RoutesAsyncClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py new file mode 100644 index 000000000000..1943383c7246 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py @@ -0,0 +1,613 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast + +from google.maps.routing_v2 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RoutesGrpcTransport +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .transports.rest import RoutesRestTransport + + +class RoutesClientMeta(type): + """Metaclass for the Routes client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] + _transport_registry["grpc"] = RoutesGrpcTransport + _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport + _transport_registry["rest"] = RoutesRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RoutesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RoutesClient(metaclass=RoutesClientMeta): + """The Routes API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "routes.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RoutesTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, RoutesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RoutesTransport): + # transport is a RoutesTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a routes_service.ComputeRoutesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, routes_service.ComputeRoutesRequest): + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_routes] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[routes_service.RouteMatrixElement]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.maps.routing_v2.types.RouteMatrixElement]: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a routes_service.ComputeRouteMatrixRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, routes_service.ComputeRouteMatrixRequest): + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RoutesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RoutesClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py new file mode 100644 index 000000000000..a15967f001c9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RoutesTransport +from .grpc import RoutesGrpcTransport +from .grpc_asyncio import RoutesGrpcAsyncIOTransport +from .rest import RoutesRestTransport +from .rest import RoutesRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] +_transport_registry['grpc'] = RoutesGrpcTransport +_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport +_transport_registry['rest'] = RoutesRestTransport + +__all__ = ( + 'RoutesTransport', + 'RoutesGrpcTransport', + 'RoutesGrpcAsyncIOTransport', + 'RoutesRestTransport', + 'RoutesRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py new file mode 100644 index 000000000000..a6fa68993eca --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.maps.routing_v2 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.maps.routing_v2.types import routes_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class RoutesTransport(abc.ABC): + """Abstract transport class for Routes.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'routes.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.compute_routes: gapic_v1.method.wrap_method( + self.compute_routes, + default_timeout=None, + client_info=client_info, + ), + self.compute_route_matrix: gapic_v1.method.wrap_method( + self.compute_route_matrix, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Union[ + routes_service.ComputeRoutesResponse, + Awaitable[routes_service.ComputeRoutesResponse] + ]]: + raise NotImplementedError() + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Union[ + routes_service.RouteMatrixElement, + Awaitable[routes_service.RouteMatrixElement] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RoutesTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py new file mode 100644 index 000000000000..8316c8b03587 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py @@ -0,0 +1,363 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO + + +class RoutesGrpcTransport(RoutesTransport): + """gRPC backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + ~.ComputeRoutesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self.grpc_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + ~.RouteMatrixElement]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RoutesGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py new file mode 100644 index 000000000000..752c5eaefc33 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO +from .grpc import RoutesGrpcTransport + + +class RoutesGrpcAsyncIOTransport(RoutesTransport): + """gRPC AsyncIO backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Awaitable[routes_service.ComputeRoutesResponse]]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + Awaitable[~.ComputeRoutesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self.grpc_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Awaitable[routes_service.RouteMatrixElement]]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + Awaitable[~.RouteMatrixElement]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'RoutesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py new file mode 100644 index 000000000000..c7fdf524b0c7 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.maps.routing_v2.types import routes_service + +from .base import RoutesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RoutesRestInterceptor: + """Interceptor for Routes. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RoutesRestTransport. + + .. code-block:: python + class MyCustomRoutesInterceptor(RoutesRestInterceptor): + def pre_compute_route_matrix(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_route_matrix(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_compute_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_routes(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) + client = RoutesClient(transport=transport) + + + """ + def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: + """Post-rpc interceptor for compute_routes + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RoutesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RoutesRestInterceptor + + +class RoutesRestTransport(RoutesTransport): + """REST backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[RoutesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RoutesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ComputeRouteMatrix(RoutesRestStub): + def __hash__(self): + return hash("ComputeRouteMatrix") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: routes_service.ComputeRouteMatrixRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + r"""Call the compute route matrix method over HTTP. + + Args: + request (~.routes_service.ComputeRouteMatrixRequest): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.routes_service.RouteMatrixElement: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/distanceMatrix/v2:computeRouteMatrix', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) + pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) + resp = self._interceptor.post_compute_route_matrix(resp) + return resp + + class _ComputeRoutes(RoutesRestStub): + def __hash__(self): + return hash("ComputeRoutes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: routes_service.ComputeRoutesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> routes_service.ComputeRoutesResponse: + r"""Call the compute routes method over HTTP. + + Args: + request (~.routes_service.ComputeRoutesRequest): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.routes_service.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/directions/v2:computeRoutes', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_compute_routes(request, metadata) + pb_request = routes_service.ComputeRoutesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = routes_service.ComputeRoutesResponse() + pb_resp = routes_service.ComputeRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_compute_routes(resp) + return resp + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RoutesRestTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py new file mode 100644 index 000000000000..7323899cfc30 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .fallback_info import ( + FallbackInfo, + FallbackReason, + FallbackRoutingMode, +) +from .geocoding_results import ( + GeocodedWaypoint, + GeocodingResults, +) +from .location import ( + Location, +) +from .navigation_instruction import ( + NavigationInstruction, +) +from .polyline import ( + Polyline, + PolylineEncoding, + PolylineQuality, +) +from .route import ( + Route, + RouteLeg, + RouteLegStep, + RouteLegStepTravelAdvisory, + RouteLegTravelAdvisory, + RouteTravelAdvisory, +) +from .route_modifiers import ( + RouteModifiers, +) +from .routes_service import ( + ComputeRouteMatrixRequest, + ComputeRoutesRequest, + ComputeRoutesResponse, + RouteMatrixDestination, + RouteMatrixElement, + RouteMatrixOrigin, + RouteMatrixElementCondition, +) +from .speed_reading_interval import ( + SpeedReadingInterval, +) +from .toll_info import ( + TollInfo, +) +from .vehicle_info import ( + VehicleInfo, +) +from .waypoint import ( + Waypoint, +) + +__all__ = ( + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py new file mode 100644 index 000000000000..99670aafac25 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'FallbackReason', + 'FallbackRoutingMode', + 'FallbackInfo', + }, +) + + +class FallbackReason(proto.Enum): + r"""Reasons for using fallback response. + + Values: + FALLBACK_REASON_UNSPECIFIED (0): + No fallback reason specified. + SERVER_ERROR (1): + A server error happened while calculating + routes with your preferred routing mode, but we + were able to return a result calculated by an + alternative mode. + LATENCY_EXCEEDED (2): + We were not able to finish the calculation + with your preferred routing mode on time, but we + were able to return a result calculated by an + alternative mode. + """ + FALLBACK_REASON_UNSPECIFIED = 0 + SERVER_ERROR = 1 + LATENCY_EXCEEDED = 2 + + +class FallbackRoutingMode(proto.Enum): + r"""Actual routing mode used for returned fallback response. + + Values: + FALLBACK_ROUTING_MODE_UNSPECIFIED (0): + Not used. + FALLBACK_TRAFFIC_UNAWARE (1): + Indicates the "TRAFFIC_UNAWARE" routing mode was used to + compute the response. + FALLBACK_TRAFFIC_AWARE (2): + Indicates the "TRAFFIC_AWARE" routing mode was used to + compute the response. + """ + FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 + FALLBACK_TRAFFIC_UNAWARE = 1 + FALLBACK_TRAFFIC_AWARE = 2 + + +class FallbackInfo(proto.Message): + r"""Information related to how and why a fallback result was + used. If this field is set, then it means the server used a + different routing mode from your preferred mode as fallback. + + Attributes: + routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): + Routing mode used for the response. If + fallback was triggered, the mode may be + different from routing preference set in the + original client request. + reason (google.maps.routing_v2.types.FallbackReason): + The reason why fallback response was used + instead of the original response. This field is + only populated when the fallback mode is + triggered and the fallback response is returned. + """ + + routing_mode: 'FallbackRoutingMode' = proto.Field( + proto.ENUM, + number=1, + enum='FallbackRoutingMode', + ) + reason: 'FallbackReason' = proto.Field( + proto.ENUM, + number=2, + enum='FallbackReason', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py new file mode 100644 index 000000000000..ffa385a59a75 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'GeocodingResults', + 'GeocodedWaypoint', + }, +) + + +class GeocodingResults(proto.Message): + r"""Contains GeocodedWaypoints for origin, destination and + intermediate waypoints. Only populated for address waypoints. + + Attributes: + origin (google.maps.routing_v2.types.GeocodedWaypoint): + Origin geocoded waypoint. + destination (google.maps.routing_v2.types.GeocodedWaypoint): + Destination geocoded waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.GeocodedWaypoint]): + A list of intermediate geocoded waypoints + each containing an index field that corresponds + to the zero-based position of the waypoint in + the order they were specified in the request. + """ + + origin: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=1, + message='GeocodedWaypoint', + ) + destination: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=2, + message='GeocodedWaypoint', + ) + intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='GeocodedWaypoint', + ) + + +class GeocodedWaypoint(proto.Message): + r"""Details about the locations used as waypoints. Only populated + for address waypoints. Includes details about the geocoding + results for the purposes of determining what the address was + geocoded to. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + geocoder_status (google.rpc.status_pb2.Status): + Indicates the status code resulting from the + geocoding operation. + intermediate_waypoint_request_index (int): + The index of the corresponding intermediate + waypoint in the request. Only populated if the + corresponding waypoint is an intermediate + waypoint. + + This field is a member of `oneof`_ ``_intermediate_waypoint_request_index``. + type_ (MutableSequence[str]): + The type(s) of the result, in the form of + zero or more type tags. Supported types: + https://developers.google.com/maps/documentation/geocoding/requests-geocoding#Types + partial_match (bool): + Indicates that the geocoder did not return an + exact match for the original request, though it + was able to match part of the requested address. + You may wish to examine the original request for + misspellings and/or an incomplete address. + place_id (str): + The place ID for this result. + """ + + geocoder_status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + intermediate_waypoint_request_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + type_: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + partial_match: bool = proto.Field( + proto.BOOL, + number=4, + ) + place_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py new file mode 100644 index 000000000000..722cd7dda46a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Location', + }, +) + + +class Location(proto.Message): + r"""Encapsulates a location (a geographic point, and an optional + heading). + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + The waypoint's geographic coordinates. + heading (google.protobuf.wrappers_pb2.Int32Value): + The compass heading associated with the direction of the + flow of traffic. This value is used to specify the side of + the road to use for pickup and drop-off. Heading values can + be from 0 to 360, where 0 specifies a heading of due North, + 90 specifies a heading of due East, etc. You can use this + field only for ``DRIVE`` and ``TWO_WHEELER`` travel modes. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + heading: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py new file mode 100644 index 000000000000..60e5cd3cb9c6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Maneuver', + }, +) + + +class Maneuver(proto.Enum): + r"""A set of values that specify the navigation action to take + for the current step (e.g., turn left, merge, straight, etc.). + + Values: + MANEUVER_UNSPECIFIED (0): + Not used. + TURN_SLIGHT_LEFT (1): + Turn slightly to the left. + TURN_SHARP_LEFT (2): + Turn sharply to the left. + UTURN_LEFT (3): + Make a left u-turn. + TURN_LEFT (4): + Turn left. + TURN_SLIGHT_RIGHT (5): + Turn slightly to the right. + TURN_SHARP_RIGHT (6): + Turn sharply to the right. + UTURN_RIGHT (7): + Make a right u-turn. + TURN_RIGHT (8): + Turn right. + STRAIGHT (9): + Go straight. + RAMP_LEFT (10): + Take the left ramp. + RAMP_RIGHT (11): + Take the right ramp. + MERGE (12): + Merge into traffic. + FORK_LEFT (13): + Take the left fork. + FORK_RIGHT (14): + Take the right fork. + FERRY (15): + Take the ferry. + FERRY_TRAIN (16): + Take the train leading onto the ferry. + ROUNDABOUT_LEFT (17): + Turn left at the roundabout. + ROUNDABOUT_RIGHT (18): + Turn right at the roundabout. + """ + MANEUVER_UNSPECIFIED = 0 + TURN_SLIGHT_LEFT = 1 + TURN_SHARP_LEFT = 2 + UTURN_LEFT = 3 + TURN_LEFT = 4 + TURN_SLIGHT_RIGHT = 5 + TURN_SHARP_RIGHT = 6 + UTURN_RIGHT = 7 + TURN_RIGHT = 8 + STRAIGHT = 9 + RAMP_LEFT = 10 + RAMP_RIGHT = 11 + MERGE = 12 + FORK_LEFT = 13 + FORK_RIGHT = 14 + FERRY = 15 + FERRY_TRAIN = 16 + ROUNDABOUT_LEFT = 17 + ROUNDABOUT_RIGHT = 18 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py new file mode 100644 index 000000000000..dc8b69e76ccd --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import maneuver as gmr_maneuver + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'NavigationInstruction', + }, +) + + +class NavigationInstruction(proto.Message): + r"""Encapsulates navigation instructions for a + [RouteLegStep][google.maps.routing.v2.RouteLegStep] + + Attributes: + maneuver (google.maps.routing_v2.types.Maneuver): + Encapsulates the navigation instructions for + the current step (e.g., turn left, merge, + straight, etc.). This field determines which + icon to display. + instructions (str): + Instructions for navigating this step. + """ + + maneuver: gmr_maneuver.Maneuver = proto.Field( + proto.ENUM, + number=1, + enum=gmr_maneuver.Maneuver, + ) + instructions: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py new file mode 100644 index 000000000000..4d9630691288 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'PolylineQuality', + 'PolylineEncoding', + 'Polyline', + }, +) + + +class PolylineQuality(proto.Enum): + r"""A set of values that specify the quality of the polyline. + + Values: + POLYLINE_QUALITY_UNSPECIFIED (0): + No polyline quality preference specified. Defaults to + ``OVERVIEW``. + HIGH_QUALITY (1): + Specifies a high-quality polyline - which is composed using + more points than ``OVERVIEW``, at the cost of increased + response size. Use this value when you need more precision. + OVERVIEW (2): + Specifies an overview polyline - which is composed using a + small number of points. Use this value when displaying an + overview of the route. Using this option has a lower request + latency compared to using the ``HIGH_QUALITY`` option. + """ + POLYLINE_QUALITY_UNSPECIFIED = 0 + HIGH_QUALITY = 1 + OVERVIEW = 2 + + +class PolylineEncoding(proto.Enum): + r"""Specifies the preferred type of polyline to be returned. + + Values: + POLYLINE_ENCODING_UNSPECIFIED (0): + No polyline type preference specified. Defaults to + ``ENCODED_POLYLINE``. + ENCODED_POLYLINE (1): + Specifies a polyline encoded using the `polyline encoding + algorithm `__. + GEO_JSON_LINESTRING (2): + Specifies a polyline using the `GeoJSON LineString + format `__ + """ + POLYLINE_ENCODING_UNSPECIFIED = 0 + ENCODED_POLYLINE = 1 + GEO_JSON_LINESTRING = 2 + + +class Polyline(proto.Message): + r"""Encapsulates an encoded polyline. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + encoded_polyline (str): + The string encoding of the polyline using the `polyline + encoding + algorithm `__ + + This field is a member of `oneof`_ ``polyline_type``. + geo_json_linestring (google.protobuf.struct_pb2.Struct): + Specifies a polyline using the `GeoJSON LineString + format `__ + + This field is a member of `oneof`_ ``polyline_type``. + """ + + encoded_polyline: str = proto.Field( + proto.STRING, + number=1, + oneof='polyline_type', + ) + geo_json_linestring: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + oneof='polyline_type', + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py new file mode 100644 index 000000000000..2a57054febff --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py @@ -0,0 +1,409 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.geo.type import viewport_pb2 # type: ignore +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction +from google.maps.routing_v2.types import polyline as gmr_polyline +from google.maps.routing_v2.types import route_label +from google.maps.routing_v2.types import speed_reading_interval +from google.maps.routing_v2.types import toll_info as gmr_toll_info +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Route', + 'RouteTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteLegStepTravelAdvisory', + 'RouteLeg', + 'RouteLegStep', + }, +) + + +class Route(proto.Message): + r"""Encapsulates a route, which consists of a series of connected + road segments that join beginning, ending, and intermediate + waypoints. + + Attributes: + route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): + Labels for the ``Route`` that are useful to identify + specific properties of the route to compare against others. + legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): + A collection of legs (path segments between waypoints) that + make-up the route. Each leg corresponds to the trip between + two non-\ ``via`` Waypoints. For example, a route with no + intermediate waypoints has only one leg. A route that + includes one non-\ ``via`` intermediate waypoint has two + legs. A route that includes one ``via`` intermediate + waypoint has one leg. The order of the legs matches the + order of Waypoints from ``origin`` to ``intermediates`` to + ``destination``. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this + value is the same as ``static_duration``. If you set the + ``routing_preference`` to either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the route + without taking traffic conditions into + consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall route polyline. This polyline will be the + combined polyline of all ``legs``. + description (str): + A description of the route. + warnings (MutableSequence[str]): + An array of warnings to show when displaying + the route. + viewport (google.geo.type.viewport_pb2.Viewport): + The viewport bounding box of the polyline. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. + route_token (str): + Web-safe base64 encoded route token that can be passed to + NavigationSDK, which allows the Navigation SDK to + reconstruct the route during navigation, and in the event of + rerouting honor the original intention when Routes + ComputeRoutes is called. Customers should treat this token + as an opaque blob. NOTE: ``Route.route_token`` is only + available for requests that have set + ``ComputeRoutesRequest.routing_preference`` to + ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. + ``Route.route_token`` is also not supported for requests + that have Via waypoints. + """ + + route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( + proto.ENUM, + number=13, + enum=route_label.RouteLabel, + ) + legs: MutableSequence['RouteLeg'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteLeg', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=2, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_polyline.Polyline, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + warnings: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + viewport: viewport_pb2.Viewport = proto.Field( + proto.MESSAGE, + number=8, + message=viewport_pb2.Viewport, + ) + travel_advisory: 'RouteTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=9, + message='RouteTravelAdvisory', + ) + route_token: str = proto.Field( + proto.STRING, + number=12, + ) + + +class RouteTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction + etc. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Encapsulates information about tolls on the Route. This + field is only populated if we expect there are tolls on the + Route. If this field is set but the estimated_price subfield + is not populated, we expect that road contains tolls but we + do not know an estimated price. If this field is not set, + then we expect there is no toll on the Route. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the route without overlap. The + start point of a specified interval is the same as the end + point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + fuel_consumption_microliters (int): + The fuel consumption prediction in + microliters. + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=speed_reading_interval.SpeedReadingInterval, + ) + fuel_consumption_microliters: int = proto.Field( + proto.INT64, + number=5, + ) + + +class RouteLegTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction + etc. on a route leg. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Encapsulates information about tolls on the specific + RouteLeg. This field is only populated if we expect there + are tolls on the RouteLeg. If this field is set but the + estimated_price subfield is not populated, we expect that + road contains tolls but we do not know an estimated price. + If this field does not exist, then there is no toll on the + RouteLeg. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the RouteLg without overlap. + The start point of a specified interval is the same as the + end point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLegStepTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction on + a leg step. + + Attributes: + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + NOTE: This field is not currently populated. + """ + + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLeg(proto.Message): + r"""Encapsulates a segment between non-\ ``via`` waypoints. + + Attributes: + distance_meters (int): + The travel distance of the route leg, in + meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the leg. If the + ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then + this value is the same as ``static_duration``. If the + ``route_preference`` is either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the leg, + calculated without taking traffic conditions + into consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall polyline for this leg. This includes that each + ``step``'s polyline. + start_location (google.maps.routing_v2.types.Location): + The start location of this leg. This might be different from + the provided ``origin``. For example, when the provided + ``origin`` is not near a road, this is a point on the road. + end_location (google.maps.routing_v2.types.Location): + The end location of this leg. This might be different from + the provided ``destination``. For example, when the provided + ``destination`` is not near a road, this is a point on the + road. + steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): + An array of steps denoting segments within + this leg. Each step represents one navigation + instruction. + travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): + Encapsulates the additional information that + the user should be informed about, such as + possible traffic zone restriction etc. on a + route leg. + """ + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=4, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=6, + message=location.Location, + ) + steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='RouteLegStep', + ) + travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=8, + message='RouteLegTravelAdvisory', + ) + + +class RouteLegStep(proto.Message): + r"""Encapsulates a segment of a ``RouteLeg``. A step corresponds to a + single navigation instruction. Route legs are made up of steps. + + Attributes: + distance_meters (int): + The travel distance of this step, in meters. + In some circumstances, this field might not have + a value. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of travel through this step + without taking traffic conditions into + consideration. In some circumstances, this field + might not have a value. + polyline (google.maps.routing_v2.types.Polyline): + The polyline associated with this step. + start_location (google.maps.routing_v2.types.Location): + The start location of this step. + end_location (google.maps.routing_v2.types.Location): + The end location of this step. + navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): + Navigation instructions. + travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): + Encapsulates the additional information that + the user should be informed about, such as + possible traffic zone restriction on a leg step. + """ + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=4, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( + proto.MESSAGE, + number=6, + message=gmr_navigation_instruction.NavigationInstruction, + ) + travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=7, + message='RouteLegStepTravelAdvisory', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py new file mode 100644 index 000000000000..a3e095209d58 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteLabel', + }, +) + + +class RouteLabel(proto.Enum): + r"""Labels for the ``Route`` that are useful to identify specific + properties of the route to compare against others. + + Values: + ROUTE_LABEL_UNSPECIFIED (0): + Default - not used. + DEFAULT_ROUTE (1): + The default "best" route returned for the + route computation. + DEFAULT_ROUTE_ALTERNATE (2): + An alternative to the default "best" route. Routes like this + will be returned when + ``ComputeRoutesRequest.compute_alternative_routes`` is + specified. + FUEL_EFFICIENT (3): + Fuel efficient route. Routes labeled with + this value are determined to be optimized for + Eco parameters such as fuel consumption. + """ + ROUTE_LABEL_UNSPECIFIED = 0 + DEFAULT_ROUTE = 1 + DEFAULT_ROUTE_ALTERNATE = 2 + FUEL_EFFICIENT = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py new file mode 100644 index 000000000000..59f5e6420c4c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import toll_passes as gmr_toll_passes +from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteModifiers', + }, +) + + +class RouteModifiers(proto.Message): + r"""Encapsulates a set of optional conditions to satisfy when + calculating the routes. + + Attributes: + avoid_tolls (bool): + Specifies whether to avoid toll roads where reasonable. + Preference will be given to routes not containing toll + roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` + travel modes. + avoid_highways (bool): + Specifies whether to avoid highways where reasonable. + Preference will be given to routes not containing highways. + Applies only to the ``DRIVE`` and ``TWO_WHEELER`` travel + modes. + avoid_ferries (bool): + Specifies whether to avoid ferries where reasonable. + Preference will be given to routes not containing travel by + ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` + travel modes. + avoid_indoor (bool): + Specifies whether to avoid navigating indoors where + reasonable. Preference will be given to routes not + containing indoor navigation. Applies only to the ``WALK`` + travel mode. + vehicle_info (google.maps.routing_v2.types.VehicleInfo): + Specifies the vehicle information. + toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): + Encapsulates information about toll passes. If toll passes + are provided, the API tries to return the pass price. If + toll passes are not provided, the API treats the toll pass + as unknown and tries to return the cash price. Applies only + to the DRIVE and TWO_WHEELER travel modes. + """ + + avoid_tolls: bool = proto.Field( + proto.BOOL, + number=1, + ) + avoid_highways: bool = proto.Field( + proto.BOOL, + number=2, + ) + avoid_ferries: bool = proto.Field( + proto.BOOL, + number=3, + ) + avoid_indoor: bool = proto.Field( + proto.BOOL, + number=4, + ) + vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_vehicle_info.VehicleInfo, + ) + toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( + proto.ENUM, + number=6, + enum=gmr_toll_passes.TollPass, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py new file mode 100644 index 000000000000..14d466006fae --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteTravelMode', + }, +) + + +class RouteTravelMode(proto.Enum): + r"""A set of values used to specify the mode of travel. NOTE: WALK, + BICYCLE, and TWO_WHEELER routes are in beta and might sometimes be + missing clear sidewalks, pedestrian paths, or bicycling paths. You + must display this warning to the user for all walking, bicycling, + and two-wheel routes that you display in your app. + + Values: + TRAVEL_MODE_UNSPECIFIED (0): + No travel mode specified. Defaults to ``DRIVE``. + DRIVE (1): + Travel by passenger car. + BICYCLE (2): + Travel by bicycle. + WALK (3): + Travel by walking. + TWO_WHEELER (4): + Two-wheeled, motorized vehicle. For example, motorcycle. + Note that this differs from the ``BICYCLE`` travel mode + which covers human-powered mode. + """ + TRAVEL_MODE_UNSPECIFIED = 0 + DRIVE = 1 + BICYCLE = 2 + WALK = 3 + TWO_WHEELER = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py new file mode 100644 index 000000000000..dffc427d20a5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import fallback_info as gmr_fallback_info +from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routing_preference as gmr_routing_preference +from google.maps.routing_v2.types import units as gmr_units +from google.maps.routing_v2.types import waypoint as gmr_waypoint +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteMatrixElementCondition', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'ComputeRouteMatrixRequest', + 'RouteMatrixOrigin', + 'RouteMatrixDestination', + 'RouteMatrixElement', + }, +) + + +class RouteMatrixElementCondition(proto.Enum): + r"""The condition of the route being returned. + + Values: + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): + Only used when the ``status`` of the element is not OK. + ROUTE_EXISTS (1): + A route was found, and the corresponding + information was filled out for the element. + ROUTE_NOT_FOUND (2): + No route could be found. Fields containing route + information, such as ``distance_meters`` or ``duration``, + will not be filled out in the element. + """ + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 + ROUTE_EXISTS = 1 + ROUTE_NOT_FOUND = 2 + + +class ComputeRoutesRequest(proto.Message): + r"""ComputeRoutes request message. + + Attributes: + origin (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint. + destination (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): + Optional. A set of waypoints along the route + (excluding terminal points), for either stopping + at or passing by. Up to 25 intermediate + waypoints are supported. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, then an error is returned. You can + specify this option only when the ``travel_mode`` is + ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. + polyline_quality (google.maps.routing_v2.types.PolylineQuality): + Optional. Specifies your preference for the + quality of the polyline. + polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): + Optional. Specifies the preferred encoding + for the polyline. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't + set this value, then this value defaults to the + time that you made the request. If you set this + value to a time that has already occurred, then + the request fails. + compute_alternative_routes (bool): + Optional. Specifies whether to calculate + alternate routes in addition to the route. No + alternative routes are returned for requests + that have intermediate waypoints. + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. A set of conditions to satisfy that + affect the way routes are calculated. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + See `Language + Support `__ + for the list of supported languages. When you don't provide + this value, the display language is inferred from the + location of the route request. + units (google.maps.routing_v2.types.Units): + Optional. Specifies the units of measure for the display + fields. This includes the ``instruction`` field in + ``NavigationInstruction``. The units of measure used for the + route, leg, step distance, and duration are not affected by + this value. If you don't provide this value, then the + display units are inferred from the location of the request. + requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): + Optional. Specifies what reference routes to calculate as + part of the request in addition to the default route. A + reference route is a route with a different route + calculation objective than the default route. For example an + FUEL_EFFICIENT reference route calculation takes into + account various parameters that would generate an optimal + fuel efficient route. + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + """ + class ReferenceRoute(proto.Enum): + r"""A supported reference route on the ComputeRoutesRequest. + + Values: + REFERENCE_ROUTE_UNSPECIFIED (0): + Not used. Requests containing this value + fail. + FUEL_EFFICIENT (1): + Fuel efficient route. Routes labeled with + this value are determined to be optimized for + parameters such as fuel consumption. + """ + REFERENCE_ROUTE_UNSPECIFIED = 0 + FUEL_EFFICIENT = 1 + + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the route(s). + FUEL_CONSUMPTION (2): + Estimated fuel consumption for the route(s). + TRAFFIC_ON_POLYLINE (3): + Traffic aware polylines for the route(s). + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + FUEL_CONSUMPTION = 2 + TRAFFIC_ON_POLYLINE = 3 + + origin: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + destination: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_waypoint.Waypoint, + ) + intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=gmr_waypoint.Waypoint, + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=4, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=5, + enum=gmr_routing_preference.RoutingPreference, + ) + polyline_quality: polyline.PolylineQuality = proto.Field( + proto.ENUM, + number=6, + enum=polyline.PolylineQuality, + ) + polyline_encoding: polyline.PolylineEncoding = proto.Field( + proto.ENUM, + number=12, + enum=polyline.PolylineEncoding, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + compute_alternative_routes: bool = proto.Field( + proto.BOOL, + number=8, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=9, + message=gmr_route_modifiers.RouteModifiers, + ) + language_code: str = proto.Field( + proto.STRING, + number=10, + ) + units: gmr_units.Units = proto.Field( + proto.ENUM, + number=11, + enum=gmr_units.Units, + ) + requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( + proto.ENUM, + number=14, + enum=ReferenceRoute, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=15, + enum=ExtraComputation, + ) + + +class ComputeRoutesResponse(proto.Message): + r"""ComputeRoutes the response message. + + Attributes: + routes (MutableSequence[google.maps.routing_v2.types.Route]): + Contains an array of computed routes (up to three) when you + specify compute_alternatives_routes, and contains just one + route when you don't. When this array contains multiple + entries, the first one is the most recommended route. If the + array is empty, then it means no route could be found. + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route results with all of the input + preferences, it may fallback to using a + different way of computation. When fallback mode + is used, this field contains detailed info about + the fallback response. Otherwise this field is + unset. + geocoding_results (google.maps.routing_v2.types.GeocodingResults): + Contains geocoding response info for + waypoints specified as addresses. + """ + + routes: MutableSequence[route.Route] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=route.Route, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_fallback_info.FallbackInfo, + ) + geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_geocoding_results.GeocodingResults, + ) + + +class ComputeRouteMatrixRequest(proto.Message): + r"""ComputeRouteMatrix request message + + Attributes: + origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): + Required. Array of origins, which determines the rows of the + response matrix. Several size restrictions apply to the + cardinality of origins and destinations: + + - The number of elements (origins × destinations) must be + no greater than 625 in any case. + - The number of elements (origins × destinations) must be + no greater than 100 if routing_preference is set to + ``TRAFFIC_AWARE_OPTIMAL``. + - The number of waypoints (origins + destinations) + specified as ``place_id`` must be no greater than 50. + destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): + Required. Array of destinations, which + determines the columns of the response matrix. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, an error is returned. You can specify + this option only when the ``travel_mode`` is ``DRIVE`` or + ``TWO_WHEELER``, otherwise the request fails. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't + set this value, this defaults to the time that + you made the request. If you set this value to a + time that has already occurred, the request + fails. + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + """ + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the matrix element(s). + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + + origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteMatrixOrigin', + ) + destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='RouteMatrixDestination', + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=3, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=4, + enum=gmr_routing_preference.RoutingPreference, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=ExtraComputation, + ) + + +class RouteMatrixOrigin(proto.Message): + r"""A single origin for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. Modifiers for every route that + takes this as the origin + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_route_modifiers.RouteModifiers, + ) + + +class RouteMatrixDestination(proto.Message): + r"""A single destination for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + + +class RouteMatrixElement(proto.Message): + r"""Encapsulates route information computed for an + origin/destination pair in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + origin_index (int): + Zero-based index of the origin in the + request. + + This field is a member of `oneof`_ ``_origin_index``. + destination_index (int): + Zero-based index of the destination in the + request. + + This field is a member of `oneof`_ ``_destination_index``. + status (google.rpc.status_pb2.Status): + Error status code for this element. + condition (google.maps.routing_v2.types.RouteMatrixElementCondition): + Indicates whether the route was found or not. + Independent of status. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this + value is the same as ``static_duration``. If you set the + ``routing_preference`` to either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the route + without taking traffic conditions into + consideration. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. For + example: restriction information and toll + information + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route with the given preferences for + this particular origin/destination pair, it may + fall back to using a different mode of + computation. When fallback mode is used, this + field contains detailed information about the + fallback response. Otherwise this field is + unset. + """ + + origin_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + destination_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + condition: 'RouteMatrixElementCondition' = proto.Field( + proto.ENUM, + number=9, + enum='RouteMatrixElementCondition', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=4, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + travel_advisory: route.RouteTravelAdvisory = proto.Field( + proto.MESSAGE, + number=7, + message=route.RouteTravelAdvisory, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=8, + message=gmr_fallback_info.FallbackInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py new file mode 100644 index 000000000000..d7d3a75786b1 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RoutingPreference', + }, +) + + +class RoutingPreference(proto.Enum): + r"""A set of values that specify factors to take into + consideration when calculating the route. + + Values: + ROUTING_PREFERENCE_UNSPECIFIED (0): + No routing preference specified. Default to + ``TRAFFIC_UNAWARE``. + TRAFFIC_UNAWARE (1): + Computes routes without taking live traffic conditions into + consideration. Suitable when traffic conditions don't matter + or are not applicable. Using this value produces the lowest + latency. Note: For ``RouteTravelMode`` DRIVE and TWO_WHEELER + choice of route and duration are based on road network and + average time-independent traffic conditions. Results for a + given request may vary over time due to changes in the road + network, updated average traffic conditions, and the + distributed nature of the service. Results may also vary + between nearly-equivalent routes at any time or frequency. + TRAFFIC_AWARE (2): + Calculates routes taking live traffic conditions into + consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, + some optimizations are applied to significantly reduce + latency. + TRAFFIC_AWARE_OPTIMAL (3): + Calculates the routes taking live traffic + conditions into consideration, without applying + most performance optimizations. Using this value + produces the highest latency. + """ + ROUTING_PREFERENCE_UNSPECIFIED = 0 + TRAFFIC_UNAWARE = 1 + TRAFFIC_AWARE = 2 + TRAFFIC_AWARE_OPTIMAL = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py new file mode 100644 index 000000000000..9a322fff1e94 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'SpeedReadingInterval', + }, +) + + +class SpeedReadingInterval(proto.Message): + r"""Traffic density indicator on a contiguous segment of a polyline or + path. Given a path with points P_0, P_1, ... , P_N (zero-based + index), the SpeedReadingInterval defines an interval and describes + its traffic using the following categories. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_polyline_point_index (int): + The starting index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_start_polyline_point_index``. + end_polyline_point_index (int): + The ending index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_end_polyline_point_index``. + speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): + Traffic speed in this interval. + """ + class Speed(proto.Enum): + r"""The classification of polyline speed based on traffic data. + + Values: + SPEED_UNSPECIFIED (0): + Default value. This value is unused. + NORMAL (1): + Normal speed, no slowdown is detected. + SLOW (2): + Slowdown detected, but no traffic jam formed. + TRAFFIC_JAM (3): + Traffic jam detected. + """ + SPEED_UNSPECIFIED = 0 + NORMAL = 1 + SLOW = 2 + TRAFFIC_JAM = 3 + + start_polyline_point_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + end_polyline_point_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + speed: Speed = proto.Field( + proto.ENUM, + number=3, + enum=Speed, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py new file mode 100644 index 000000000000..3182bd03ac01 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.type import money_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TollInfo', + }, +) + + +class TollInfo(proto.Message): + r"""Encapsulates toll information on a ``Route`` or on a ``RouteLeg``. + + Attributes: + estimated_price (MutableSequence[google.type.money_pb2.Money]): + The monetary amount of tolls for the + corresponding Route or RouteLeg. This list + contains a money amount for each currency that + is expected to be charged by the toll stations. + Typically this list will contain only one item + for routes with tolls in one currency. For + international trips, this list may contain + multiple items to reflect tolls in different + currencies. + """ + + estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=money_pb2.Money, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py new file mode 100644 index 000000000000..05edb1a082c3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py @@ -0,0 +1,348 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TollPass', + }, +) + + +class TollPass(proto.Enum): + r"""List of toll passes around the world that we support. + + Values: + TOLL_PASS_UNSPECIFIED (0): + Not used. If this value is used, then the + request fails. + AU_ETOLL_TAG (82): + Sydney toll pass. See additional details at + https://www.myetoll.com.au. + AU_EWAY_TAG (83): + Sydney toll pass. See additional details at + https://www.tollpay.com.au. + AU_LINKT (2): + Australia-wide toll pass. + See additional details at + https://www.linkt.com.au/. + AR_TELEPASE (3): + Argentina toll pass. See additional details + at https://telepase.com.ar + BR_AUTO_EXPRESO (81): + Brazil toll pass. See additional details at + https://www.autoexpreso.com + BR_CONECTCAR (7): + Brazil toll pass. See additional details at + https://conectcar.com. + BR_MOVE_MAIS (8): + Brazil toll pass. See additional details at + https://movemais.com. + BR_PASSA_RAPIDO (88): + Brazil toll pass. See additional details at + https://pasorapido.gob.do/ + BR_SEM_PARAR (9): + Brazil toll pass. See additional details at + https://www.semparar.com.br. + BR_TAGGY (10): + Brazil toll pass. See additional details at + https://taggy.com.br. + BR_VELOE (11): + Brazil toll pass. See additional details at + https://veloe.com.br/site/onde-usar. + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): + Canada to United States border crossing. + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): + Canada to United States border crossing. + CA_US_BLUE_WATER_EDGE_PASS (18): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_CONNEXION (19): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_NEXUS_CARD (20): + Canada to United States border crossing. + ID_E_TOLL (16): + Indonesia. + E-card provided by multiple banks used to pay + for tolls. All e-cards via banks are charged the + same so only one enum value is needed. E.g. - + Bank Mandiri + https://www.bankmandiri.co.id/e-money - BCA + https://www.bca.co.id/flazz + - BNI + https://www.bni.co.id/id-id/ebanking/tapcash + IN_FASTAG (78): + India. + IN_LOCAL_HP_PLATE_EXEMPT (79): + India, HP state plate exemption. + MX_IAVE (90): + Mexico toll pass. + https://iave.capufe.gob.mx/#/ + MX_PASE (91): + Mexico + https://www.pase.com.mx + MX_QUICKPASS (93): + Mexico + https://operadoravial.com/quick-pass/ + MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): + http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf + MX_TAG_IAVE (12): + Mexico + MX_TAG_TELEVIA (13): + Mexico toll pass company. One of many + operating in Mexico City. See additional details + at https://www.televia.com.mx. + MX_TELEVIA (92): + Mexico toll pass company. One of many + operating in Mexico City. + https://www.televia.com.mx + MX_VIAPASS (14): + Mexico toll pass. See additional details at + https://www.viapass.com.mx/viapass/web_home.aspx. + US_AL_FREEDOM_PASS (21): + AL, USA. + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): + AK, USA. + US_CA_FASTRAK (4): + CA, USA. + US_CA_FASTRAK_CAV_STICKER (86): + Indicates driver has any FasTrak pass in + addition to the DMV issued Clean Air Vehicle + (CAV) sticker. + https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml + US_CO_EXPRESSTOLL (23): + CO, USA. + US_CO_GO_PASS (24): + CO, USA. + US_DE_EZPASSDE (25): + DE, USA. + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): + FL, USA. + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): + FL, USA. + US_FL_EPASS (67): + FL, USA. + US_FL_GIBA_TOLL_PASS (68): + FL, USA. + US_FL_LEEWAY (69): + FL, USA. + US_FL_SUNPASS (70): + FL, USA. + US_FL_SUNPASS_PRO (71): + FL, USA. + US_IL_EZPASSIL (73): + IL, USA. + US_IL_IPASS (72): + IL, USA. + US_IN_EZPASSIN (26): + IN, USA. + US_KS_BESTPASS_HORIZON (27): + KS, USA. + US_KS_KTAG (28): + KS, USA. + US_KS_NATIONALPASS (29): + KS, USA. + US_KS_PREPASS_ELITEPASS (30): + KS, USA. + US_KY_RIVERLINK (31): + KY, USA. + US_LA_GEAUXPASS (32): + LA, USA. + US_LA_TOLL_TAG (33): + LA, USA. + US_MA_EZPASSMA (6): + MA, USA. + US_MD_EZPASSMD (34): + MD, USA. + US_ME_EZPASSME (35): + ME, USA. + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): + MI, USA. + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): + MI, USA. + US_MI_IQ_PROX_CARD (38): + MI, USA. + US_MI_MACKINAC_BRIDGE_MAC_PASS (39): + MI, USA. + US_MI_NEXPRESS_TOLL (40): + MI, USA. + US_MN_EZPASSMN (41): + MN, USA. + US_NC_EZPASSNC (42): + NC, USA. + US_NC_PEACH_PASS (87): + NC, USA. + US_NC_QUICK_PASS (43): + NC, USA. + US_NH_EZPASSNH (80): + NH, USA. + US_NJ_DOWNBEACH_EXPRESS_PASS (75): + NJ, USA. + US_NJ_EZPASSNJ (74): + NJ, USA. + US_NY_EXPRESSPASS (76): + NY, USA. + US_NY_EZPASSNY (77): + NY, USA. + US_OH_EZPASSOH (44): + OH, USA. + US_PA_EZPASSPA (45): + PA, USA. + US_RI_EZPASSRI (46): + RI, USA. + US_SC_PALPASS (47): + SC, USA. + US_TX_BANCPASS (48): + TX, USA. + US_TX_DEL_RIO_PASS (49): + TX, USA. + US_TX_EFAST_PASS (50): + TX, USA. + US_TX_EAGLE_PASS_EXPRESS_CARD (51): + TX, USA. + US_TX_EPTOLL (52): + TX, USA. + US_TX_EZ_CROSS (53): + TX, USA. + US_TX_EZTAG (54): + TX, USA. + US_TX_LAREDO_TRADE_TAG (55): + TX, USA. + US_TX_PLUSPASS (56): + TX, USA. + US_TX_TOLLTAG (57): + TX, USA. + US_TX_TXTAG (58): + TX, USA. + US_TX_XPRESS_CARD (59): + TX, USA. + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): + UT, USA. + US_VA_EZPASSVA (61): + VA, USA. + US_WA_BREEZEBY (17): + WA, USA. + US_WA_GOOD_TO_GO (1): + WA, USA. + US_WV_EZPASSWV (62): + WV, USA. + US_WV_MEMORIAL_BRIDGE_TICKETS (63): + WV, USA. + US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): + WV, USA. + """ + TOLL_PASS_UNSPECIFIED = 0 + AU_ETOLL_TAG = 82 + AU_EWAY_TAG = 83 + AU_LINKT = 2 + AR_TELEPASE = 3 + BR_AUTO_EXPRESO = 81 + BR_CONECTCAR = 7 + BR_MOVE_MAIS = 8 + BR_PASSA_RAPIDO = 88 + BR_SEM_PARAR = 9 + BR_TAGGY = 10 + BR_VELOE = 11 + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 + CA_US_BLUE_WATER_EDGE_PASS = 18 + CA_US_CONNEXION = 19 + CA_US_NEXUS_CARD = 20 + ID_E_TOLL = 16 + IN_FASTAG = 78 + IN_LOCAL_HP_PLATE_EXEMPT = 79 + MX_IAVE = 90 + MX_PASE = 91 + MX_QUICKPASS = 93 + MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 + MX_TAG_IAVE = 12 + MX_TAG_TELEVIA = 13 + MX_TELEVIA = 92 + MX_VIAPASS = 14 + US_AL_FREEDOM_PASS = 21 + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 + US_CA_FASTRAK = 4 + US_CA_FASTRAK_CAV_STICKER = 86 + US_CO_EXPRESSTOLL = 23 + US_CO_GO_PASS = 24 + US_DE_EZPASSDE = 25 + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 + US_FL_EPASS = 67 + US_FL_GIBA_TOLL_PASS = 68 + US_FL_LEEWAY = 69 + US_FL_SUNPASS = 70 + US_FL_SUNPASS_PRO = 71 + US_IL_EZPASSIL = 73 + US_IL_IPASS = 72 + US_IN_EZPASSIN = 26 + US_KS_BESTPASS_HORIZON = 27 + US_KS_KTAG = 28 + US_KS_NATIONALPASS = 29 + US_KS_PREPASS_ELITEPASS = 30 + US_KY_RIVERLINK = 31 + US_LA_GEAUXPASS = 32 + US_LA_TOLL_TAG = 33 + US_MA_EZPASSMA = 6 + US_MD_EZPASSMD = 34 + US_ME_EZPASSME = 35 + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 + US_MI_IQ_PROX_CARD = 38 + US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 + US_MI_NEXPRESS_TOLL = 40 + US_MN_EZPASSMN = 41 + US_NC_EZPASSNC = 42 + US_NC_PEACH_PASS = 87 + US_NC_QUICK_PASS = 43 + US_NH_EZPASSNH = 80 + US_NJ_DOWNBEACH_EXPRESS_PASS = 75 + US_NJ_EZPASSNJ = 74 + US_NY_EXPRESSPASS = 76 + US_NY_EZPASSNY = 77 + US_OH_EZPASSOH = 44 + US_PA_EZPASSPA = 45 + US_RI_EZPASSRI = 46 + US_SC_PALPASS = 47 + US_TX_BANCPASS = 48 + US_TX_DEL_RIO_PASS = 49 + US_TX_EFAST_PASS = 50 + US_TX_EAGLE_PASS_EXPRESS_CARD = 51 + US_TX_EPTOLL = 52 + US_TX_EZ_CROSS = 53 + US_TX_EZTAG = 54 + US_TX_LAREDO_TRADE_TAG = 55 + US_TX_PLUSPASS = 56 + US_TX_TOLLTAG = 57 + US_TX_TXTAG = 58 + US_TX_XPRESS_CARD = 59 + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 + US_VA_EZPASSVA = 61 + US_WA_BREEZEBY = 17 + US_WA_GOOD_TO_GO = 1 + US_WV_EZPASSWV = 62 + US_WV_MEMORIAL_BRIDGE_TICKETS = 63 + US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py new file mode 100644 index 000000000000..93cfaf1ee04c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Units', + }, +) + + +class Units(proto.Enum): + r"""A set of values that specify the unit of measure used in the + display. + + Values: + UNITS_UNSPECIFIED (0): + Units of measure not specified. Defaults to + the unit of measure inferred from the request. + METRIC (1): + Metric units of measure. + IMPERIAL (2): + Imperial (English) units of measure. + """ + UNITS_UNSPECIFIED = 0 + METRIC = 1 + IMPERIAL = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py new file mode 100644 index 000000000000..a94a99025c80 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'VehicleEmissionType', + }, +) + + +class VehicleEmissionType(proto.Enum): + r"""A set of values describing the vehicle's emission type. + Applies only to the DRIVE travel mode. + + Values: + VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): + No emission type specified. Default to + GASOLINE. + GASOLINE (1): + Gasoline/petrol fueled vehicle. + ELECTRIC (2): + Electricity powered vehicle. + HYBRID (3): + Hybrid fuel (such as gasoline + electric) + vehicle. + DIESEL (4): + Diesel fueled vehicle. + """ + VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 + GASOLINE = 1 + ELECTRIC = 2 + HYBRID = 3 + DIESEL = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py new file mode 100644 index 000000000000..2d71bb0a70a0 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import vehicle_emission_type + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'VehicleInfo', + }, +) + + +class VehicleInfo(proto.Message): + r"""Encapsulates the vehicle information, such as the license + plate last character. + + Attributes: + emission_type (google.maps.routing_v2.types.VehicleEmissionType): + Describes the vehicle's emission type. + Applies only to the DRIVE travel mode. + """ + + emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( + proto.ENUM, + number=2, + enum=vehicle_emission_type.VehicleEmissionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py new file mode 100644 index 000000000000..c25013cfd086 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import location as gmr_location + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Waypoint', + }, +) + + +class Waypoint(proto.Message): + r"""Encapsulates a waypoint. Waypoints mark both the beginning + and end of a route, and include intermediate stops along the + route. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location (google.maps.routing_v2.types.Location): + A point specified using geographic + coordinates, including an optional heading. + + This field is a member of `oneof`_ ``location_type``. + place_id (str): + The POI Place ID associated with the + waypoint. + + This field is a member of `oneof`_ ``location_type``. + address (str): + Human readable address or a plus code. + See https://plus.codes for details. + + This field is a member of `oneof`_ ``location_type``. + via (bool): + Marks this waypoint as a milestone rather a stopping point. + For each non-via waypoint in the request, the response + appends an entry to the ``legs`` array to provide the + details for stopovers on that leg of the trip. Set this + value to true when you want the route to pass through this + waypoint without stopping over. Via waypoints don't cause an + entry to be added to the ``legs`` array, but they do route + the journey through the waypoint. You can only set this + value on waypoints that are intermediates. The request fails + if you set this field on terminal waypoints. If + ``ComputeRoutesRequest.optimize_waypoint_order`` is set to + true then this field cannot be set to true; otherwise, the + request fails. + vehicle_stopover (bool): + Indicates that the waypoint is meant for vehicles to stop + at, where the intention is to either pickup or drop-off. + When you set this value, the calculated route won't include + non-\ ``via`` waypoints on roads that are unsuitable for + pickup and drop-off. This option works only for ``DRIVE`` + and ``TWO_WHEELER`` travel modes, and when the + ``location_type`` is ``location``. + side_of_road (bool): + Indicates that the location of this waypoint is meant to + have a preference for the vehicle to stop at a particular + side of road. When you set this value, the route will pass + through the location so that the vehicle can stop at the + side of road that the location is biased towards from the + center of the road. This option works only for 'DRIVE' and + 'TWO_WHEELER' travel modes. + """ + + location: gmr_location.Location = proto.Field( + proto.MESSAGE, + number=1, + oneof='location_type', + message=gmr_location.Location, + ) + place_id: str = proto.Field( + proto.STRING, + number=2, + oneof='location_type', + ) + address: str = proto.Field( + proto.STRING, + number=7, + oneof='location_type', + ) + via: bool = proto.Field( + proto.BOOL, + number=3, + ) + vehicle_stopover: bool = proto.Field( + proto.BOOL, + number=4, + ) + side_of_road: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py new file mode 100644 index 000000000000..59757e684c85 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/routing_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py new file mode 100644 index 000000000000..381f53f7a26e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py new file mode 100644 index 000000000000..125691404b0b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py new file mode 100644 index 000000000000..c978c3e55cd7 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py new file mode 100644 index 000000000000..ca13730e4ddc --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json new file mode 100644 index 000000000000..b5ed5aca319c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json @@ -0,0 +1,321 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.routing.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-maps-routing", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_route_matrix_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_route_matrix_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_routes_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py new file mode 100644 index 000000000000..291c4ea93db5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class routingCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'extra_computations', ), + 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'units', 'requested_reference_routes', 'extra_computations', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=routingCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the routing client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py new file mode 100644 index 000000000000..1047dfef360b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-maps-routing' + + +description = "Google Maps Routing API client library" + +version = {} +with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-maps-routing" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.maps"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt new file mode 100644 index 000000000000..6c44adfea7ee --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py new file mode 100644 index 000000000000..55f7b3a4ba31 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py @@ -0,0 +1,1750 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.maps.routing_v2.services.routes import RoutesAsyncClient +from google.maps.routing_v2.services.routes import RoutesClient +from google.maps.routing_v2.services.routes import transports +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routes_service +from google.maps.routing_v2.types import routing_preference +from google.maps.routing_v2.types import toll_passes +from google.maps.routing_v2.types import units +from google.maps.routing_v2.types import vehicle_emission_type +from google.maps.routing_v2.types import vehicle_info +from google.maps.routing_v2.types import waypoint +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +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 RoutesClient._get_default_mtls_endpoint(None) is None + assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RoutesGrpcTransport, "grpc"), + (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RoutesRestTransport, "rest"), +]) +def test_routes_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +def test_routes_client_get_transport_class(): + transport = RoutesClient.get_transport_class() + available_transports = [ + transports.RoutesGrpcTransport, + transports.RoutesRestTransport, + ] + assert transport in available_transports + + transport = RoutesClient.get_transport_class("grpc") + assert transport == transports.RoutesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +def test_routes_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RoutesClient, transports.RoutesRestTransport, "rest", "true"), + (RoutesClient, transports.RoutesRestTransport, "rest", "false"), +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_routes_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + RoutesClient, RoutesAsyncClient +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +def test_routes_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +def test_routes_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RoutesClient, transports.RoutesRestTransport, "rest", None), +]) +def test_routes_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_routes_client_client_options_from_dict(): + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RoutesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_routes_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "routes.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes(request_type, transport: str = 'grpc'): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = routes_service.ComputeRoutesResponse( + ) + response = client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + client.compute_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + +@pytest.mark.asyncio +async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( + )) + response = await client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +@pytest.mark.asyncio +async def test_compute_routes_async_from_dict(): + await test_compute_routes_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix(request_type, transport: str = 'grpc'): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([routes_service.RouteMatrixElement()]) + response = client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, routes_service.RouteMatrixElement) + + +def test_compute_route_matrix_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + client.compute_route_matrix() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + +@pytest.mark.asyncio +async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) + response = await client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, routes_service.RouteMatrixElement) + + +@pytest.mark.asyncio +async def test_compute_route_matrix_async_from_dict(): + await test_compute_route_matrix_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes_rest(request_type): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = routes_service.ComputeRoutesResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.compute_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): + transport_class = transports.RoutesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.ComputeRoutesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.compute_routes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_routes_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_routes._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_routes_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) + + request = routes_service.ComputeRoutesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.ComputeRoutesResponse() + + client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_routes_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRoutesRequest): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.compute_routes(request) + + +def test_compute_routes_rest_error(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix_rest(request_type): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = routes_service.RouteMatrixElement( + origin_index=1279, + destination_index=1817, + condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, + distance_meters=1594, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.compute_route_matrix(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.RouteMatrixElement) + assert response.origin_index == 1279 + assert response.destination_index == 1817 + assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS + assert response.distance_meters == 1594 + + +def test_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): + transport_class = transports.RoutesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.RouteMatrixElement() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.compute_route_matrix(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_route_matrix_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_route_matrix_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) + req.return_value._content = "[{}]".format(req.return_value._content) + + request = routes_service.ComputeRouteMatrixRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.RouteMatrixElement() + + client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_route_matrix_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.compute_route_matrix(request) + + +def test_compute_route_matrix_rest_error(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutesClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RoutesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RoutesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = RoutesClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RoutesGrpcTransport, + ) + +def test_routes_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_routes_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'compute_routes', + 'compute_route_matrix', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_routes_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +def test_routes_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport() + adc.assert_called_once() + + +def test_routes_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RoutesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + ], +) +def test_routes_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, + ], +) +def test_routes_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RoutesGrpcTransport, grpc_helpers), + (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_routes_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "routes.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_routes_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.RoutesRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_routes_host_no_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_routes_host_with_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_routes_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RoutesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RoutesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.compute_routes._session + session2 = client2.transport.compute_routes._session + assert session1 != session2 + session1 = client1.transport.compute_route_matrix._session + session2 = client2.transport.compute_route_matrix._session + assert session1 != session2 +def test_routes_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_routes_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + 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 + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + 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=cred, + credentials_file=None, + scopes=None, + 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 + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_transport_channel_mtls_with_adc( + transport_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), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + 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 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RoutesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RoutesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = RoutesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RoutesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RoutesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RoutesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = RoutesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RoutesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RoutesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RoutesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: + transport_class = RoutesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (RoutesClient, transports.RoutesGrpcTransport), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From 42f694b66572ffcf6f6b27fda05a410596fb53e0 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 10 Mar 2023 20:51:05 +0000 Subject: [PATCH 04/12] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../google-maps-routing/v2/.coveragerc | 13 - .../google-maps-routing/v2/.flake8 | 33 - .../google-maps-routing/v2/MANIFEST.in | 2 - .../google-maps-routing/v2/README.rst | 49 - .../google-maps-routing/v2/docs/conf.py | 376 ---- .../google-maps-routing/v2/docs/index.rst | 7 - .../v2/docs/routing_v2/routes.rst | 6 - .../v2/docs/routing_v2/services.rst | 6 - .../v2/docs/routing_v2/types.rst | 6 - .../v2/google/maps/routing/__init__.py | 97 - .../v2/google/maps/routing/gapic_version.py | 16 - .../v2/google/maps/routing/py.typed | 2 - .../v2/google/maps/routing_v2/__init__.py | 98 - .../maps/routing_v2/gapic_metadata.json | 58 - .../google/maps/routing_v2/gapic_version.py | 16 - .../v2/google/maps/routing_v2/py.typed | 2 - .../maps/routing_v2/services/__init__.py | 15 - .../routing_v2/services/routes/__init__.py | 22 - .../services/routes/async_client.py | 416 ---- .../maps/routing_v2/services/routes/client.py | 613 ------ .../services/routes/transports/__init__.py | 38 - .../services/routes/transports/base.py | 161 -- .../services/routes/transports/grpc.py | 363 ---- .../routes/transports/grpc_asyncio.py | 362 ---- .../services/routes/transports/rest.py | 417 ---- .../google/maps/routing_v2/types/__init__.py | 105 - .../maps/routing_v2/types/fallback_info.py | 103 - .../routing_v2/types/geocoding_results.py | 125 -- .../google/maps/routing_v2/types/location.py | 62 - .../google/maps/routing_v2/types/maneuver.py | 96 - .../types/navigation_instruction.py | 58 - .../google/maps/routing_v2/types/polyline.py | 113 -- .../v2/google/maps/routing_v2/types/route.py | 409 ---- .../maps/routing_v2/types/route_label.py | 57 - .../maps/routing_v2/types/route_modifiers.py | 97 - .../routing_v2/types/route_travel_mode.py | 59 - .../maps/routing_v2/types/routes_service.py | 512 ----- .../routing_v2/types/routing_preference.py | 67 - .../types/speed_reading_interval.py | 89 - .../google/maps/routing_v2/types/toll_info.py | 56 - .../maps/routing_v2/types/toll_passes.py | 348 ---- .../v2/google/maps/routing_v2/types/units.py | 49 - .../routing_v2/types/vehicle_emission_type.py | 56 - .../maps/routing_v2/types/vehicle_info.py | 50 - .../google/maps/routing_v2/types/waypoint.py | 123 -- .../google-maps-routing/v2/mypy.ini | 3 - .../google-maps-routing/v2/noxfile.py | 184 -- ...rated_routes_compute_route_matrix_async.py | 52 - ...erated_routes_compute_route_matrix_sync.py | 52 - ...2_generated_routes_compute_routes_async.py | 51 - ...v2_generated_routes_compute_routes_sync.py | 51 - ...ippet_metadata_google.maps.routing.v2.json | 321 --- .../v2/scripts/fixup_routing_v2_keywords.py | 177 -- .../google-maps-routing/v2/setup.py | 90 - .../v2/testing/constraints-3.10.txt | 6 - .../v2/testing/constraints-3.11.txt | 6 - .../v2/testing/constraints-3.12.txt | 6 - .../v2/testing/constraints-3.7.txt | 9 - .../v2/testing/constraints-3.8.txt | 6 - .../v2/testing/constraints-3.9.txt | 6 - .../google-maps-routing/v2/tests/__init__.py | 16 - .../v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/routing_v2/__init__.py | 16 - .../unit/gapic/routing_v2/test_routes.py | 1750 ----------------- .../maps/routing_v2/types/routes_service.py | 4 +- 66 files changed, 3 insertions(+), 8663 deletions(-) delete mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc delete mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 delete mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini delete mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py diff --git a/owl-bot-staging/google-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc deleted file mode 100644 index d0ce5597b0a9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/routing/__init__.py - google/maps/routing/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.flake8 +++ /dev/null @@ -1,33 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in deleted file mode 100644 index c5b56c111c00..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/routing *.py -recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst deleted file mode 100644 index f0002366e552..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Routing API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Maps Routing API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py deleted file mode 100644 index d7a10abed96b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-maps-routing documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -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"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-maps-routing" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# 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"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# 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 - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -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 = { - "description": "Google Maps Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# 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 - -# 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 - -# 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, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# 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 = [] - -# 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' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is 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 = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# 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' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# 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' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-maps-routing-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- 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', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-maps-routing.tex", - u"google-maps-routing 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 - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# 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 = [ - ( - root_doc, - "google-maps-routing", - u"Google Maps Routing Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-maps-routing", - u"google-maps-routing Documentation", - author, - "google-maps-routing", - "GAPIC library for Google Maps Routing API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# 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), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst deleted file mode 100644 index e2563dd88ee9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - routing_v2/services - routing_v2/types diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst deleted file mode 100644 index 3d52309cddae..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst +++ /dev/null @@ -1,6 +0,0 @@ -Routes ------------------------- - -.. automodule:: google.maps.routing_v2.services.routes - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst deleted file mode 100644 index e96568dc434c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Routing v2 API -======================================= -.. toctree:: - :maxdepth: 2 - - routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst deleted file mode 100644 index 176a5a812cf8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Routing v2 API -==================================== - -.. automodule:: google.maps.routing_v2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py deleted file mode 100644 index 59020a3484c3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.maps.routing import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.routing_v2.services.routes.client import RoutesClient -from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient - -from google.maps.routing_v2.types.fallback_info import FallbackInfo -from google.maps.routing_v2.types.fallback_info import FallbackReason -from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode -from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint -from google.maps.routing_v2.types.geocoding_results import GeocodingResults -from google.maps.routing_v2.types.location import Location -from google.maps.routing_v2.types.maneuver import Maneuver -from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction -from google.maps.routing_v2.types.polyline import Polyline -from google.maps.routing_v2.types.polyline import PolylineEncoding -from google.maps.routing_v2.types.polyline import PolylineQuality -from google.maps.routing_v2.types.route import Route -from google.maps.routing_v2.types.route import RouteLeg -from google.maps.routing_v2.types.route import RouteLegStep -from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory -from google.maps.routing_v2.types.route import RouteLegTravelAdvisory -from google.maps.routing_v2.types.route import RouteTravelAdvisory -from google.maps.routing_v2.types.route_label import RouteLabel -from google.maps.routing_v2.types.route_modifiers import RouteModifiers -from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode -from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse -from google.maps.routing_v2.types.routes_service import RouteMatrixDestination -from google.maps.routing_v2.types.routes_service import RouteMatrixElement -from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin -from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition -from google.maps.routing_v2.types.routing_preference import RoutingPreference -from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval -from google.maps.routing_v2.types.toll_info import TollInfo -from google.maps.routing_v2.types.toll_passes import TollPass -from google.maps.routing_v2.types.units import Units -from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType -from google.maps.routing_v2.types.vehicle_info import VehicleInfo -from google.maps.routing_v2.types.waypoint import Waypoint - -__all__ = ('RoutesClient', - 'RoutesAsyncClient', - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py deleted file mode 100644 index 405b1cebcf15..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py deleted file mode 100644 index cd9d694f63c6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.maps.routing_v2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.routes import RoutesClient -from .services.routes import RoutesAsyncClient - -from .types.fallback_info import FallbackInfo -from .types.fallback_info import FallbackReason -from .types.fallback_info import FallbackRoutingMode -from .types.geocoding_results import GeocodedWaypoint -from .types.geocoding_results import GeocodingResults -from .types.location import Location -from .types.maneuver import Maneuver -from .types.navigation_instruction import NavigationInstruction -from .types.polyline import Polyline -from .types.polyline import PolylineEncoding -from .types.polyline import PolylineQuality -from .types.route import Route -from .types.route import RouteLeg -from .types.route import RouteLegStep -from .types.route import RouteLegStepTravelAdvisory -from .types.route import RouteLegTravelAdvisory -from .types.route import RouteTravelAdvisory -from .types.route_label import RouteLabel -from .types.route_modifiers import RouteModifiers -from .types.route_travel_mode import RouteTravelMode -from .types.routes_service import ComputeRouteMatrixRequest -from .types.routes_service import ComputeRoutesRequest -from .types.routes_service import ComputeRoutesResponse -from .types.routes_service import RouteMatrixDestination -from .types.routes_service import RouteMatrixElement -from .types.routes_service import RouteMatrixOrigin -from .types.routes_service import RouteMatrixElementCondition -from .types.routing_preference import RoutingPreference -from .types.speed_reading_interval import SpeedReadingInterval -from .types.toll_info import TollInfo -from .types.toll_passes import TollPass -from .types.units import Units -from .types.vehicle_emission_type import VehicleEmissionType -from .types.vehicle_info import VehicleInfo -from .types.waypoint import Waypoint - -__all__ = ( - 'RoutesAsyncClient', -'ComputeRouteMatrixRequest', -'ComputeRoutesRequest', -'ComputeRoutesResponse', -'FallbackInfo', -'FallbackReason', -'FallbackRoutingMode', -'GeocodedWaypoint', -'GeocodingResults', -'Location', -'Maneuver', -'NavigationInstruction', -'Polyline', -'PolylineEncoding', -'PolylineQuality', -'Route', -'RouteLabel', -'RouteLeg', -'RouteLegStep', -'RouteLegStepTravelAdvisory', -'RouteLegTravelAdvisory', -'RouteMatrixDestination', -'RouteMatrixElement', -'RouteMatrixElementCondition', -'RouteMatrixOrigin', -'RouteModifiers', -'RouteTravelAdvisory', -'RouteTravelMode', -'RoutesClient', -'RoutingPreference', -'SpeedReadingInterval', -'TollInfo', -'TollPass', -'Units', -'VehicleEmissionType', -'VehicleInfo', -'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json deleted file mode 100644 index 8382cea1d39a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json +++ /dev/null @@ -1,58 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.routing_v2", - "protoPackage": "google.maps.routing.v2", - "schema": "1.0", - "services": { - "Routes": { - "clients": { - "grpc": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RoutesAsyncClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "rest": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py deleted file mode 100644 index 405b1cebcf15..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py deleted file mode 100644 index e8e1c3845db5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py deleted file mode 100644 index ff3f8f71863f..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import RoutesClient -from .async_client import RoutesAsyncClient - -__all__ = ( - 'RoutesClient', - 'RoutesAsyncClient', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py deleted file mode 100644 index 7f8df74a140b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union - -from google.maps.routing_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .client import RoutesClient - - -class RoutesAsyncClient: - """The Routes API.""" - - _client: RoutesClient - - DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RoutesClient.common_folder_path) - parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) - common_organization_path = staticmethod(RoutesClient.common_organization_path) - parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) - common_project_path = staticmethod(RoutesClient.common_project_path) - parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) - common_location_path = staticmethod(RoutesClient.common_location_path) - parse_common_location_path = staticmethod(RoutesClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(RoutesClient).get_transport_class, type(RoutesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, RoutesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.RoutesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RoutesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # Create or coerce a protobuf request object. - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.compute_routes, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - # Create or coerce a protobuf request object. - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.compute_route_matrix, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RoutesAsyncClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py deleted file mode 100644 index 1943383c7246..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py +++ /dev/null @@ -1,613 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast - -from google.maps.routing_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RoutesGrpcTransport -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .transports.rest import RoutesRestTransport - - -class RoutesClientMeta(type): - """Metaclass for the Routes client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] - _transport_registry["grpc"] = RoutesGrpcTransport - _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport - _transport_registry["rest"] = RoutesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RoutesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class RoutesClient(metaclass=RoutesClientMeta): - """The Routes API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "routes.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RoutesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, RoutesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, RoutesTransport): - # transport is a RoutesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a routes_service.ComputeRoutesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, routes_service.ComputeRoutesRequest): - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_routes] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[routes_service.RouteMatrixElement]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - Iterable[google.maps.routing_v2.types.RouteMatrixElement]: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a routes_service.ComputeRouteMatrixRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, routes_service.ComputeRouteMatrixRequest): - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "RoutesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RoutesClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py deleted file mode 100644 index a15967f001c9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import RoutesTransport -from .grpc import RoutesGrpcTransport -from .grpc_asyncio import RoutesGrpcAsyncIOTransport -from .rest import RoutesRestTransport -from .rest import RoutesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] -_transport_registry['grpc'] = RoutesGrpcTransport -_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport -_transport_registry['rest'] = RoutesRestTransport - -__all__ = ( - 'RoutesTransport', - 'RoutesGrpcTransport', - 'RoutesGrpcAsyncIOTransport', - 'RoutesRestTransport', - 'RoutesRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py deleted file mode 100644 index a6fa68993eca..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py +++ /dev/null @@ -1,161 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.maps.routing_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.maps.routing_v2.types import routes_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class RoutesTransport(abc.ABC): - """Abstract transport class for Routes.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'routes.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.compute_routes: gapic_v1.method.wrap_method( - self.compute_routes, - default_timeout=None, - client_info=client_info, - ), - self.compute_route_matrix: gapic_v1.method.wrap_method( - self.compute_route_matrix, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Union[ - routes_service.ComputeRoutesResponse, - Awaitable[routes_service.ComputeRoutesResponse] - ]]: - raise NotImplementedError() - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Union[ - routes_service.RouteMatrixElement, - Awaitable[routes_service.RouteMatrixElement] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RoutesTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py deleted file mode 100644 index 8316c8b03587..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py +++ /dev/null @@ -1,363 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO - - -class RoutesGrpcTransport(RoutesTransport): - """gRPC backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - ~.ComputeRoutesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self.grpc_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - ~.RouteMatrixElement]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RoutesGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py deleted file mode 100644 index 752c5eaefc33..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py +++ /dev/null @@ -1,362 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO -from .grpc import RoutesGrpcTransport - - -class RoutesGrpcAsyncIOTransport(RoutesTransport): - """gRPC AsyncIO backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Awaitable[routes_service.ComputeRoutesResponse]]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - Awaitable[~.ComputeRoutesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self.grpc_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Awaitable[routes_service.RouteMatrixElement]]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - Awaitable[~.RouteMatrixElement]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'RoutesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py deleted file mode 100644 index c7fdf524b0c7..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.maps.routing_v2.types import routes_service - -from .base import RoutesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class RoutesRestInterceptor: - """Interceptor for Routes. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the RoutesRestTransport. - - .. code-block:: python - class MyCustomRoutesInterceptor(RoutesRestInterceptor): - def pre_compute_route_matrix(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_route_matrix(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_compute_routes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_routes(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) - client = RoutesClient(transport=transport) - - - """ - def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: - """Post-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compute_routes - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: - """Post-rpc interceptor for compute_routes - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class RoutesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RoutesRestInterceptor - - -class RoutesRestTransport(RoutesTransport): - """REST backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[RoutesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or RoutesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ComputeRouteMatrix(RoutesRestStub): - def __hash__(self): - return hash("ComputeRouteMatrix") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: routes_service.ComputeRouteMatrixRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> rest_streaming.ResponseIterator: - r"""Call the compute route matrix method over HTTP. - - Args: - request (~.routes_service.ComputeRouteMatrixRequest): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.routes_service.RouteMatrixElement: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/distanceMatrix/v2:computeRouteMatrix', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) - pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) - resp = self._interceptor.post_compute_route_matrix(resp) - return resp - - class _ComputeRoutes(RoutesRestStub): - def __hash__(self): - return hash("ComputeRoutes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: routes_service.ComputeRoutesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> routes_service.ComputeRoutesResponse: - r"""Call the compute routes method over HTTP. - - Args: - request (~.routes_service.ComputeRoutesRequest): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.routes_service.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/directions/v2:computeRoutes', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_compute_routes(request, metadata) - pb_request = routes_service.ComputeRoutesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = routes_service.ComputeRoutesResponse() - pb_resp = routes_service.ComputeRoutesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_compute_routes(resp) - return resp - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RoutesRestTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py deleted file mode 100644 index 7323899cfc30..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .fallback_info import ( - FallbackInfo, - FallbackReason, - FallbackRoutingMode, -) -from .geocoding_results import ( - GeocodedWaypoint, - GeocodingResults, -) -from .location import ( - Location, -) -from .navigation_instruction import ( - NavigationInstruction, -) -from .polyline import ( - Polyline, - PolylineEncoding, - PolylineQuality, -) -from .route import ( - Route, - RouteLeg, - RouteLegStep, - RouteLegStepTravelAdvisory, - RouteLegTravelAdvisory, - RouteTravelAdvisory, -) -from .route_modifiers import ( - RouteModifiers, -) -from .routes_service import ( - ComputeRouteMatrixRequest, - ComputeRoutesRequest, - ComputeRoutesResponse, - RouteMatrixDestination, - RouteMatrixElement, - RouteMatrixOrigin, - RouteMatrixElementCondition, -) -from .speed_reading_interval import ( - SpeedReadingInterval, -) -from .toll_info import ( - TollInfo, -) -from .vehicle_info import ( - VehicleInfo, -) -from .waypoint import ( - Waypoint, -) - -__all__ = ( - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py deleted file mode 100644 index 99670aafac25..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'FallbackReason', - 'FallbackRoutingMode', - 'FallbackInfo', - }, -) - - -class FallbackReason(proto.Enum): - r"""Reasons for using fallback response. - - Values: - FALLBACK_REASON_UNSPECIFIED (0): - No fallback reason specified. - SERVER_ERROR (1): - A server error happened while calculating - routes with your preferred routing mode, but we - were able to return a result calculated by an - alternative mode. - LATENCY_EXCEEDED (2): - We were not able to finish the calculation - with your preferred routing mode on time, but we - were able to return a result calculated by an - alternative mode. - """ - FALLBACK_REASON_UNSPECIFIED = 0 - SERVER_ERROR = 1 - LATENCY_EXCEEDED = 2 - - -class FallbackRoutingMode(proto.Enum): - r"""Actual routing mode used for returned fallback response. - - Values: - FALLBACK_ROUTING_MODE_UNSPECIFIED (0): - Not used. - FALLBACK_TRAFFIC_UNAWARE (1): - Indicates the "TRAFFIC_UNAWARE" routing mode was used to - compute the response. - FALLBACK_TRAFFIC_AWARE (2): - Indicates the "TRAFFIC_AWARE" routing mode was used to - compute the response. - """ - FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 - FALLBACK_TRAFFIC_UNAWARE = 1 - FALLBACK_TRAFFIC_AWARE = 2 - - -class FallbackInfo(proto.Message): - r"""Information related to how and why a fallback result was - used. If this field is set, then it means the server used a - different routing mode from your preferred mode as fallback. - - Attributes: - routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): - Routing mode used for the response. If - fallback was triggered, the mode may be - different from routing preference set in the - original client request. - reason (google.maps.routing_v2.types.FallbackReason): - The reason why fallback response was used - instead of the original response. This field is - only populated when the fallback mode is - triggered and the fallback response is returned. - """ - - routing_mode: 'FallbackRoutingMode' = proto.Field( - proto.ENUM, - number=1, - enum='FallbackRoutingMode', - ) - reason: 'FallbackReason' = proto.Field( - proto.ENUM, - number=2, - enum='FallbackReason', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py deleted file mode 100644 index ffa385a59a75..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py +++ /dev/null @@ -1,125 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'GeocodingResults', - 'GeocodedWaypoint', - }, -) - - -class GeocodingResults(proto.Message): - r"""Contains GeocodedWaypoints for origin, destination and - intermediate waypoints. Only populated for address waypoints. - - Attributes: - origin (google.maps.routing_v2.types.GeocodedWaypoint): - Origin geocoded waypoint. - destination (google.maps.routing_v2.types.GeocodedWaypoint): - Destination geocoded waypoint. - intermediates (MutableSequence[google.maps.routing_v2.types.GeocodedWaypoint]): - A list of intermediate geocoded waypoints - each containing an index field that corresponds - to the zero-based position of the waypoint in - the order they were specified in the request. - """ - - origin: 'GeocodedWaypoint' = proto.Field( - proto.MESSAGE, - number=1, - message='GeocodedWaypoint', - ) - destination: 'GeocodedWaypoint' = proto.Field( - proto.MESSAGE, - number=2, - message='GeocodedWaypoint', - ) - intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='GeocodedWaypoint', - ) - - -class GeocodedWaypoint(proto.Message): - r"""Details about the locations used as waypoints. Only populated - for address waypoints. Includes details about the geocoding - results for the purposes of determining what the address was - geocoded to. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - geocoder_status (google.rpc.status_pb2.Status): - Indicates the status code resulting from the - geocoding operation. - intermediate_waypoint_request_index (int): - The index of the corresponding intermediate - waypoint in the request. Only populated if the - corresponding waypoint is an intermediate - waypoint. - - This field is a member of `oneof`_ ``_intermediate_waypoint_request_index``. - type_ (MutableSequence[str]): - The type(s) of the result, in the form of - zero or more type tags. Supported types: - https://developers.google.com/maps/documentation/geocoding/requests-geocoding#Types - partial_match (bool): - Indicates that the geocoder did not return an - exact match for the original request, though it - was able to match part of the requested address. - You may wish to examine the original request for - misspellings and/or an incomplete address. - place_id (str): - The place ID for this result. - """ - - geocoder_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - intermediate_waypoint_request_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - type_: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - partial_match: bool = proto.Field( - proto.BOOL, - number=4, - ) - place_id: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py deleted file mode 100644 index 722cd7dda46a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Location', - }, -) - - -class Location(proto.Message): - r"""Encapsulates a location (a geographic point, and an optional - heading). - - Attributes: - lat_lng (google.type.latlng_pb2.LatLng): - The waypoint's geographic coordinates. - heading (google.protobuf.wrappers_pb2.Int32Value): - The compass heading associated with the direction of the - flow of traffic. This value is used to specify the side of - the road to use for pickup and drop-off. Heading values can - be from 0 to 360, where 0 specifies a heading of due North, - 90 specifies a heading of due East, etc. You can use this - field only for ``DRIVE`` and ``TWO_WHEELER`` travel modes. - """ - - lat_lng: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - heading: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py deleted file mode 100644 index 60e5cd3cb9c6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Maneuver', - }, -) - - -class Maneuver(proto.Enum): - r"""A set of values that specify the navigation action to take - for the current step (e.g., turn left, merge, straight, etc.). - - Values: - MANEUVER_UNSPECIFIED (0): - Not used. - TURN_SLIGHT_LEFT (1): - Turn slightly to the left. - TURN_SHARP_LEFT (2): - Turn sharply to the left. - UTURN_LEFT (3): - Make a left u-turn. - TURN_LEFT (4): - Turn left. - TURN_SLIGHT_RIGHT (5): - Turn slightly to the right. - TURN_SHARP_RIGHT (6): - Turn sharply to the right. - UTURN_RIGHT (7): - Make a right u-turn. - TURN_RIGHT (8): - Turn right. - STRAIGHT (9): - Go straight. - RAMP_LEFT (10): - Take the left ramp. - RAMP_RIGHT (11): - Take the right ramp. - MERGE (12): - Merge into traffic. - FORK_LEFT (13): - Take the left fork. - FORK_RIGHT (14): - Take the right fork. - FERRY (15): - Take the ferry. - FERRY_TRAIN (16): - Take the train leading onto the ferry. - ROUNDABOUT_LEFT (17): - Turn left at the roundabout. - ROUNDABOUT_RIGHT (18): - Turn right at the roundabout. - """ - MANEUVER_UNSPECIFIED = 0 - TURN_SLIGHT_LEFT = 1 - TURN_SHARP_LEFT = 2 - UTURN_LEFT = 3 - TURN_LEFT = 4 - TURN_SLIGHT_RIGHT = 5 - TURN_SHARP_RIGHT = 6 - UTURN_RIGHT = 7 - TURN_RIGHT = 8 - STRAIGHT = 9 - RAMP_LEFT = 10 - RAMP_RIGHT = 11 - MERGE = 12 - FORK_LEFT = 13 - FORK_RIGHT = 14 - FERRY = 15 - FERRY_TRAIN = 16 - ROUNDABOUT_LEFT = 17 - ROUNDABOUT_RIGHT = 18 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py deleted file mode 100644 index dc8b69e76ccd..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import maneuver as gmr_maneuver - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'NavigationInstruction', - }, -) - - -class NavigationInstruction(proto.Message): - r"""Encapsulates navigation instructions for a - [RouteLegStep][google.maps.routing.v2.RouteLegStep] - - Attributes: - maneuver (google.maps.routing_v2.types.Maneuver): - Encapsulates the navigation instructions for - the current step (e.g., turn left, merge, - straight, etc.). This field determines which - icon to display. - instructions (str): - Instructions for navigating this step. - """ - - maneuver: gmr_maneuver.Maneuver = proto.Field( - proto.ENUM, - number=1, - enum=gmr_maneuver.Maneuver, - ) - instructions: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py deleted file mode 100644 index 4d9630691288..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'PolylineQuality', - 'PolylineEncoding', - 'Polyline', - }, -) - - -class PolylineQuality(proto.Enum): - r"""A set of values that specify the quality of the polyline. - - Values: - POLYLINE_QUALITY_UNSPECIFIED (0): - No polyline quality preference specified. Defaults to - ``OVERVIEW``. - HIGH_QUALITY (1): - Specifies a high-quality polyline - which is composed using - more points than ``OVERVIEW``, at the cost of increased - response size. Use this value when you need more precision. - OVERVIEW (2): - Specifies an overview polyline - which is composed using a - small number of points. Use this value when displaying an - overview of the route. Using this option has a lower request - latency compared to using the ``HIGH_QUALITY`` option. - """ - POLYLINE_QUALITY_UNSPECIFIED = 0 - HIGH_QUALITY = 1 - OVERVIEW = 2 - - -class PolylineEncoding(proto.Enum): - r"""Specifies the preferred type of polyline to be returned. - - Values: - POLYLINE_ENCODING_UNSPECIFIED (0): - No polyline type preference specified. Defaults to - ``ENCODED_POLYLINE``. - ENCODED_POLYLINE (1): - Specifies a polyline encoded using the `polyline encoding - algorithm `__. - GEO_JSON_LINESTRING (2): - Specifies a polyline using the `GeoJSON LineString - format `__ - """ - POLYLINE_ENCODING_UNSPECIFIED = 0 - ENCODED_POLYLINE = 1 - GEO_JSON_LINESTRING = 2 - - -class Polyline(proto.Message): - r"""Encapsulates an encoded polyline. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - encoded_polyline (str): - The string encoding of the polyline using the `polyline - encoding - algorithm `__ - - This field is a member of `oneof`_ ``polyline_type``. - geo_json_linestring (google.protobuf.struct_pb2.Struct): - Specifies a polyline using the `GeoJSON LineString - format `__ - - This field is a member of `oneof`_ ``polyline_type``. - """ - - encoded_polyline: str = proto.Field( - proto.STRING, - number=1, - oneof='polyline_type', - ) - geo_json_linestring: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - oneof='polyline_type', - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py deleted file mode 100644 index 2a57054febff..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py +++ /dev/null @@ -1,409 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.geo.type import viewport_pb2 # type: ignore -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction -from google.maps.routing_v2.types import polyline as gmr_polyline -from google.maps.routing_v2.types import route_label -from google.maps.routing_v2.types import speed_reading_interval -from google.maps.routing_v2.types import toll_info as gmr_toll_info -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Route', - 'RouteTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteLegStepTravelAdvisory', - 'RouteLeg', - 'RouteLegStep', - }, -) - - -class Route(proto.Message): - r"""Encapsulates a route, which consists of a series of connected - road segments that join beginning, ending, and intermediate - waypoints. - - Attributes: - route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): - Labels for the ``Route`` that are useful to identify - specific properties of the route to compare against others. - legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): - A collection of legs (path segments between waypoints) that - make-up the route. Each leg corresponds to the trip between - two non-\ ``via`` Waypoints. For example, a route with no - intermediate waypoints has only one leg. A route that - includes one non-\ ``via`` intermediate waypoint has two - legs. A route that includes one ``via`` intermediate - waypoint has one leg. The order of the legs matches the - order of Waypoints from ``origin`` to ``intermediates`` to - ``destination``. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the route - without taking traffic conditions into - consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall route polyline. This polyline will be the - combined polyline of all ``legs``. - description (str): - A description of the route. - warnings (MutableSequence[str]): - An array of warnings to show when displaying - the route. - viewport (google.geo.type.viewport_pb2.Viewport): - The viewport bounding box of the polyline. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. - route_token (str): - Web-safe base64 encoded route token that can be passed to - NavigationSDK, which allows the Navigation SDK to - reconstruct the route during navigation, and in the event of - rerouting honor the original intention when Routes - ComputeRoutes is called. Customers should treat this token - as an opaque blob. NOTE: ``Route.route_token`` is only - available for requests that have set - ``ComputeRoutesRequest.routing_preference`` to - ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. - ``Route.route_token`` is also not supported for requests - that have Via waypoints. - """ - - route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( - proto.ENUM, - number=13, - enum=route_label.RouteLabel, - ) - legs: MutableSequence['RouteLeg'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteLeg', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=2, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_polyline.Polyline, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - warnings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - viewport: viewport_pb2.Viewport = proto.Field( - proto.MESSAGE, - number=8, - message=viewport_pb2.Viewport, - ) - travel_advisory: 'RouteTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=9, - message='RouteTravelAdvisory', - ) - route_token: str = proto.Field( - proto.STRING, - number=12, - ) - - -class RouteTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction - etc. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Encapsulates information about tolls on the Route. This - field is only populated if we expect there are tolls on the - Route. If this field is set but the estimated_price subfield - is not populated, we expect that road contains tolls but we - do not know an estimated price. If this field is not set, - then we expect there is no toll on the Route. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the route without overlap. The - start point of a specified interval is the same as the end - point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - fuel_consumption_microliters (int): - The fuel consumption prediction in - microliters. - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=speed_reading_interval.SpeedReadingInterval, - ) - fuel_consumption_microliters: int = proto.Field( - proto.INT64, - number=5, - ) - - -class RouteLegTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction - etc. on a route leg. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Encapsulates information about tolls on the specific - RouteLeg. This field is only populated if we expect there - are tolls on the RouteLeg. If this field is set but the - estimated_price subfield is not populated, we expect that - road contains tolls but we do not know an estimated price. - If this field does not exist, then there is no toll on the - RouteLeg. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the RouteLg without overlap. - The start point of a specified interval is the same as the - end point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLegStepTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction on - a leg step. - - Attributes: - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - NOTE: This field is not currently populated. - """ - - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLeg(proto.Message): - r"""Encapsulates a segment between non-\ ``via`` waypoints. - - Attributes: - distance_meters (int): - The travel distance of the route leg, in - meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the leg. If the - ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then - this value is the same as ``static_duration``. If the - ``route_preference`` is either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the leg, - calculated without taking traffic conditions - into consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall polyline for this leg. This includes that each - ``step``'s polyline. - start_location (google.maps.routing_v2.types.Location): - The start location of this leg. This might be different from - the provided ``origin``. For example, when the provided - ``origin`` is not near a road, this is a point on the road. - end_location (google.maps.routing_v2.types.Location): - The end location of this leg. This might be different from - the provided ``destination``. For example, when the provided - ``destination`` is not near a road, this is a point on the - road. - steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): - An array of steps denoting segments within - this leg. Each step represents one navigation - instruction. - travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): - Encapsulates the additional information that - the user should be informed about, such as - possible traffic zone restriction etc. on a - route leg. - """ - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=4, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=6, - message=location.Location, - ) - steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='RouteLegStep', - ) - travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=8, - message='RouteLegTravelAdvisory', - ) - - -class RouteLegStep(proto.Message): - r"""Encapsulates a segment of a ``RouteLeg``. A step corresponds to a - single navigation instruction. Route legs are made up of steps. - - Attributes: - distance_meters (int): - The travel distance of this step, in meters. - In some circumstances, this field might not have - a value. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of travel through this step - without taking traffic conditions into - consideration. In some circumstances, this field - might not have a value. - polyline (google.maps.routing_v2.types.Polyline): - The polyline associated with this step. - start_location (google.maps.routing_v2.types.Location): - The start location of this step. - end_location (google.maps.routing_v2.types.Location): - The end location of this step. - navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): - Navigation instructions. - travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): - Encapsulates the additional information that - the user should be informed about, such as - possible traffic zone restriction on a leg step. - """ - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=4, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( - proto.MESSAGE, - number=6, - message=gmr_navigation_instruction.NavigationInstruction, - ) - travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=7, - message='RouteLegStepTravelAdvisory', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py deleted file mode 100644 index a3e095209d58..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteLabel', - }, -) - - -class RouteLabel(proto.Enum): - r"""Labels for the ``Route`` that are useful to identify specific - properties of the route to compare against others. - - Values: - ROUTE_LABEL_UNSPECIFIED (0): - Default - not used. - DEFAULT_ROUTE (1): - The default "best" route returned for the - route computation. - DEFAULT_ROUTE_ALTERNATE (2): - An alternative to the default "best" route. Routes like this - will be returned when - ``ComputeRoutesRequest.compute_alternative_routes`` is - specified. - FUEL_EFFICIENT (3): - Fuel efficient route. Routes labeled with - this value are determined to be optimized for - Eco parameters such as fuel consumption. - """ - ROUTE_LABEL_UNSPECIFIED = 0 - DEFAULT_ROUTE = 1 - DEFAULT_ROUTE_ALTERNATE = 2 - FUEL_EFFICIENT = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py deleted file mode 100644 index 59f5e6420c4c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import toll_passes as gmr_toll_passes -from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteModifiers', - }, -) - - -class RouteModifiers(proto.Message): - r"""Encapsulates a set of optional conditions to satisfy when - calculating the routes. - - Attributes: - avoid_tolls (bool): - Specifies whether to avoid toll roads where reasonable. - Preference will be given to routes not containing toll - roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - travel modes. - avoid_highways (bool): - Specifies whether to avoid highways where reasonable. - Preference will be given to routes not containing highways. - Applies only to the ``DRIVE`` and ``TWO_WHEELER`` travel - modes. - avoid_ferries (bool): - Specifies whether to avoid ferries where reasonable. - Preference will be given to routes not containing travel by - ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` - travel modes. - avoid_indoor (bool): - Specifies whether to avoid navigating indoors where - reasonable. Preference will be given to routes not - containing indoor navigation. Applies only to the ``WALK`` - travel mode. - vehicle_info (google.maps.routing_v2.types.VehicleInfo): - Specifies the vehicle information. - toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): - Encapsulates information about toll passes. If toll passes - are provided, the API tries to return the pass price. If - toll passes are not provided, the API treats the toll pass - as unknown and tries to return the cash price. Applies only - to the DRIVE and TWO_WHEELER travel modes. - """ - - avoid_tolls: bool = proto.Field( - proto.BOOL, - number=1, - ) - avoid_highways: bool = proto.Field( - proto.BOOL, - number=2, - ) - avoid_ferries: bool = proto.Field( - proto.BOOL, - number=3, - ) - avoid_indoor: bool = proto.Field( - proto.BOOL, - number=4, - ) - vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_vehicle_info.VehicleInfo, - ) - toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( - proto.ENUM, - number=6, - enum=gmr_toll_passes.TollPass, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py deleted file mode 100644 index 14d466006fae..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteTravelMode', - }, -) - - -class RouteTravelMode(proto.Enum): - r"""A set of values used to specify the mode of travel. NOTE: WALK, - BICYCLE, and TWO_WHEELER routes are in beta and might sometimes be - missing clear sidewalks, pedestrian paths, or bicycling paths. You - must display this warning to the user for all walking, bicycling, - and two-wheel routes that you display in your app. - - Values: - TRAVEL_MODE_UNSPECIFIED (0): - No travel mode specified. Defaults to ``DRIVE``. - DRIVE (1): - Travel by passenger car. - BICYCLE (2): - Travel by bicycle. - WALK (3): - Travel by walking. - TWO_WHEELER (4): - Two-wheeled, motorized vehicle. For example, motorcycle. - Note that this differs from the ``BICYCLE`` travel mode - which covers human-powered mode. - """ - TRAVEL_MODE_UNSPECIFIED = 0 - DRIVE = 1 - BICYCLE = 2 - WALK = 3 - TWO_WHEELER = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py deleted file mode 100644 index dffc427d20a5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py +++ /dev/null @@ -1,512 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import fallback_info as gmr_fallback_info -from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routing_preference as gmr_routing_preference -from google.maps.routing_v2.types import units as gmr_units -from google.maps.routing_v2.types import waypoint as gmr_waypoint -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteMatrixElementCondition', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'ComputeRouteMatrixRequest', - 'RouteMatrixOrigin', - 'RouteMatrixDestination', - 'RouteMatrixElement', - }, -) - - -class RouteMatrixElementCondition(proto.Enum): - r"""The condition of the route being returned. - - Values: - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): - Only used when the ``status`` of the element is not OK. - ROUTE_EXISTS (1): - A route was found, and the corresponding - information was filled out for the element. - ROUTE_NOT_FOUND (2): - No route could be found. Fields containing route - information, such as ``distance_meters`` or ``duration``, - will not be filled out in the element. - """ - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 - ROUTE_EXISTS = 1 - ROUTE_NOT_FOUND = 2 - - -class ComputeRoutesRequest(proto.Message): - r"""ComputeRoutes request message. - - Attributes: - origin (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint. - destination (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint. - intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): - Optional. A set of waypoints along the route - (excluding terminal points), for either stopping - at or passing by. Up to 25 intermediate - waypoints are supported. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, then an error is returned. You can - specify this option only when the ``travel_mode`` is - ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. - polyline_quality (google.maps.routing_v2.types.PolylineQuality): - Optional. Specifies your preference for the - quality of the polyline. - polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): - Optional. Specifies the preferred encoding - for the polyline. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't - set this value, then this value defaults to the - time that you made the request. If you set this - value to a time that has already occurred, then - the request fails. - compute_alternative_routes (bool): - Optional. Specifies whether to calculate - alternate routes in addition to the route. No - alternative routes are returned for requests - that have intermediate waypoints. - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. A set of conditions to satisfy that - affect the way routes are calculated. - language_code (str): - Optional. The BCP-47 language code, such as "en-US" or - "sr-Latn". For more information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - See `Language - Support `__ - for the list of supported languages. When you don't provide - this value, the display language is inferred from the - location of the route request. - units (google.maps.routing_v2.types.Units): - Optional. Specifies the units of measure for the display - fields. This includes the ``instruction`` field in - ``NavigationInstruction``. The units of measure used for the - route, leg, step distance, and duration are not affected by - this value. If you don't provide this value, then the - display units are inferred from the location of the request. - requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): - Optional. Specifies what reference routes to calculate as - part of the request in addition to the default route. A - reference route is a route with a different route - calculation objective than the default route. For example an - FUEL_EFFICIENT reference route calculation takes into - account various parameters that would generate an optimal - fuel efficient route. - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - """ - class ReferenceRoute(proto.Enum): - r"""A supported reference route on the ComputeRoutesRequest. - - Values: - REFERENCE_ROUTE_UNSPECIFIED (0): - Not used. Requests containing this value - fail. - FUEL_EFFICIENT (1): - Fuel efficient route. Routes labeled with - this value are determined to be optimized for - parameters such as fuel consumption. - """ - REFERENCE_ROUTE_UNSPECIFIED = 0 - FUEL_EFFICIENT = 1 - - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the route(s). - FUEL_CONSUMPTION (2): - Estimated fuel consumption for the route(s). - TRAFFIC_ON_POLYLINE (3): - Traffic aware polylines for the route(s). - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - FUEL_CONSUMPTION = 2 - TRAFFIC_ON_POLYLINE = 3 - - origin: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - destination: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_waypoint.Waypoint, - ) - intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=gmr_waypoint.Waypoint, - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=4, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=5, - enum=gmr_routing_preference.RoutingPreference, - ) - polyline_quality: polyline.PolylineQuality = proto.Field( - proto.ENUM, - number=6, - enum=polyline.PolylineQuality, - ) - polyline_encoding: polyline.PolylineEncoding = proto.Field( - proto.ENUM, - number=12, - enum=polyline.PolylineEncoding, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - compute_alternative_routes: bool = proto.Field( - proto.BOOL, - number=8, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=9, - message=gmr_route_modifiers.RouteModifiers, - ) - language_code: str = proto.Field( - proto.STRING, - number=10, - ) - units: gmr_units.Units = proto.Field( - proto.ENUM, - number=11, - enum=gmr_units.Units, - ) - requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( - proto.ENUM, - number=14, - enum=ReferenceRoute, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=15, - enum=ExtraComputation, - ) - - -class ComputeRoutesResponse(proto.Message): - r"""ComputeRoutes the response message. - - Attributes: - routes (MutableSequence[google.maps.routing_v2.types.Route]): - Contains an array of computed routes (up to three) when you - specify compute_alternatives_routes, and contains just one - route when you don't. When this array contains multiple - entries, the first one is the most recommended route. If the - array is empty, then it means no route could be found. - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route results with all of the input - preferences, it may fallback to using a - different way of computation. When fallback mode - is used, this field contains detailed info about - the fallback response. Otherwise this field is - unset. - geocoding_results (google.maps.routing_v2.types.GeocodingResults): - Contains geocoding response info for - waypoints specified as addresses. - """ - - routes: MutableSequence[route.Route] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=route.Route, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_fallback_info.FallbackInfo, - ) - geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_geocoding_results.GeocodingResults, - ) - - -class ComputeRouteMatrixRequest(proto.Message): - r"""ComputeRouteMatrix request message - - Attributes: - origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): - Required. Array of origins, which determines the rows of the - response matrix. Several size restrictions apply to the - cardinality of origins and destinations: - - - The number of elements (origins × destinations) must be - no greater than 625 in any case. - - The number of elements (origins × destinations) must be - no greater than 100 if routing_preference is set to - ``TRAFFIC_AWARE_OPTIMAL``. - - The number of waypoints (origins + destinations) - specified as ``place_id`` must be no greater than 50. - destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): - Required. Array of destinations, which - determines the columns of the response matrix. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, an error is returned. You can specify - this option only when the ``travel_mode`` is ``DRIVE`` or - ``TWO_WHEELER``, otherwise the request fails. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't - set this value, this defaults to the time that - you made the request. If you set this value to a - time that has already occurred, the request - fails. - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - """ - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the matrix element(s). - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - - origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteMatrixOrigin', - ) - destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='RouteMatrixDestination', - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=3, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=4, - enum=gmr_routing_preference.RoutingPreference, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=8, - enum=ExtraComputation, - ) - - -class RouteMatrixOrigin(proto.Message): - r"""A single origin for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. Modifiers for every route that - takes this as the origin - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_route_modifiers.RouteModifiers, - ) - - -class RouteMatrixDestination(proto.Message): - r"""A single destination for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - - -class RouteMatrixElement(proto.Message): - r"""Encapsulates route information computed for an - origin/destination pair in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - origin_index (int): - Zero-based index of the origin in the - request. - - This field is a member of `oneof`_ ``_origin_index``. - destination_index (int): - Zero-based index of the destination in the - request. - - This field is a member of `oneof`_ ``_destination_index``. - status (google.rpc.status_pb2.Status): - Error status code for this element. - condition (google.maps.routing_v2.types.RouteMatrixElementCondition): - Indicates whether the route was found or not. - Independent of status. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the route - without taking traffic conditions into - consideration. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. For - example: restriction information and toll - information - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route with the given preferences for - this particular origin/destination pair, it may - fall back to using a different mode of - computation. When fallback mode is used, this - field contains detailed information about the - fallback response. Otherwise this field is - unset. - """ - - origin_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - destination_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - condition: 'RouteMatrixElementCondition' = proto.Field( - proto.ENUM, - number=9, - enum='RouteMatrixElementCondition', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=4, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - travel_advisory: route.RouteTravelAdvisory = proto.Field( - proto.MESSAGE, - number=7, - message=route.RouteTravelAdvisory, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=8, - message=gmr_fallback_info.FallbackInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py deleted file mode 100644 index d7d3a75786b1..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RoutingPreference', - }, -) - - -class RoutingPreference(proto.Enum): - r"""A set of values that specify factors to take into - consideration when calculating the route. - - Values: - ROUTING_PREFERENCE_UNSPECIFIED (0): - No routing preference specified. Default to - ``TRAFFIC_UNAWARE``. - TRAFFIC_UNAWARE (1): - Computes routes without taking live traffic conditions into - consideration. Suitable when traffic conditions don't matter - or are not applicable. Using this value produces the lowest - latency. Note: For ``RouteTravelMode`` DRIVE and TWO_WHEELER - choice of route and duration are based on road network and - average time-independent traffic conditions. Results for a - given request may vary over time due to changes in the road - network, updated average traffic conditions, and the - distributed nature of the service. Results may also vary - between nearly-equivalent routes at any time or frequency. - TRAFFIC_AWARE (2): - Calculates routes taking live traffic conditions into - consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, - some optimizations are applied to significantly reduce - latency. - TRAFFIC_AWARE_OPTIMAL (3): - Calculates the routes taking live traffic - conditions into consideration, without applying - most performance optimizations. Using this value - produces the highest latency. - """ - ROUTING_PREFERENCE_UNSPECIFIED = 0 - TRAFFIC_UNAWARE = 1 - TRAFFIC_AWARE = 2 - TRAFFIC_AWARE_OPTIMAL = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py deleted file mode 100644 index 9a322fff1e94..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'SpeedReadingInterval', - }, -) - - -class SpeedReadingInterval(proto.Message): - r"""Traffic density indicator on a contiguous segment of a polyline or - path. Given a path with points P_0, P_1, ... , P_N (zero-based - index), the SpeedReadingInterval defines an interval and describes - its traffic using the following categories. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - start_polyline_point_index (int): - The starting index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_start_polyline_point_index``. - end_polyline_point_index (int): - The ending index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_end_polyline_point_index``. - speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): - Traffic speed in this interval. - """ - class Speed(proto.Enum): - r"""The classification of polyline speed based on traffic data. - - Values: - SPEED_UNSPECIFIED (0): - Default value. This value is unused. - NORMAL (1): - Normal speed, no slowdown is detected. - SLOW (2): - Slowdown detected, but no traffic jam formed. - TRAFFIC_JAM (3): - Traffic jam detected. - """ - SPEED_UNSPECIFIED = 0 - NORMAL = 1 - SLOW = 2 - TRAFFIC_JAM = 3 - - start_polyline_point_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - end_polyline_point_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - speed: Speed = proto.Field( - proto.ENUM, - number=3, - enum=Speed, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py deleted file mode 100644 index 3182bd03ac01..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.type import money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TollInfo', - }, -) - - -class TollInfo(proto.Message): - r"""Encapsulates toll information on a ``Route`` or on a ``RouteLeg``. - - Attributes: - estimated_price (MutableSequence[google.type.money_pb2.Money]): - The monetary amount of tolls for the - corresponding Route or RouteLeg. This list - contains a money amount for each currency that - is expected to be charged by the toll stations. - Typically this list will contain only one item - for routes with tolls in one currency. For - international trips, this list may contain - multiple items to reflect tolls in different - currencies. - """ - - estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=money_pb2.Money, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py deleted file mode 100644 index 05edb1a082c3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py +++ /dev/null @@ -1,348 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TollPass', - }, -) - - -class TollPass(proto.Enum): - r"""List of toll passes around the world that we support. - - Values: - TOLL_PASS_UNSPECIFIED (0): - Not used. If this value is used, then the - request fails. - AU_ETOLL_TAG (82): - Sydney toll pass. See additional details at - https://www.myetoll.com.au. - AU_EWAY_TAG (83): - Sydney toll pass. See additional details at - https://www.tollpay.com.au. - AU_LINKT (2): - Australia-wide toll pass. - See additional details at - https://www.linkt.com.au/. - AR_TELEPASE (3): - Argentina toll pass. See additional details - at https://telepase.com.ar - BR_AUTO_EXPRESO (81): - Brazil toll pass. See additional details at - https://www.autoexpreso.com - BR_CONECTCAR (7): - Brazil toll pass. See additional details at - https://conectcar.com. - BR_MOVE_MAIS (8): - Brazil toll pass. See additional details at - https://movemais.com. - BR_PASSA_RAPIDO (88): - Brazil toll pass. See additional details at - https://pasorapido.gob.do/ - BR_SEM_PARAR (9): - Brazil toll pass. See additional details at - https://www.semparar.com.br. - BR_TAGGY (10): - Brazil toll pass. See additional details at - https://taggy.com.br. - BR_VELOE (11): - Brazil toll pass. See additional details at - https://veloe.com.br/site/onde-usar. - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): - Canada to United States border crossing. - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): - Canada to United States border crossing. - CA_US_BLUE_WATER_EDGE_PASS (18): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_CONNEXION (19): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_NEXUS_CARD (20): - Canada to United States border crossing. - ID_E_TOLL (16): - Indonesia. - E-card provided by multiple banks used to pay - for tolls. All e-cards via banks are charged the - same so only one enum value is needed. E.g. - - Bank Mandiri - https://www.bankmandiri.co.id/e-money - BCA - https://www.bca.co.id/flazz - - BNI - https://www.bni.co.id/id-id/ebanking/tapcash - IN_FASTAG (78): - India. - IN_LOCAL_HP_PLATE_EXEMPT (79): - India, HP state plate exemption. - MX_IAVE (90): - Mexico toll pass. - https://iave.capufe.gob.mx/#/ - MX_PASE (91): - Mexico - https://www.pase.com.mx - MX_QUICKPASS (93): - Mexico - https://operadoravial.com/quick-pass/ - MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): - http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf - MX_TAG_IAVE (12): - Mexico - MX_TAG_TELEVIA (13): - Mexico toll pass company. One of many - operating in Mexico City. See additional details - at https://www.televia.com.mx. - MX_TELEVIA (92): - Mexico toll pass company. One of many - operating in Mexico City. - https://www.televia.com.mx - MX_VIAPASS (14): - Mexico toll pass. See additional details at - https://www.viapass.com.mx/viapass/web_home.aspx. - US_AL_FREEDOM_PASS (21): - AL, USA. - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): - AK, USA. - US_CA_FASTRAK (4): - CA, USA. - US_CA_FASTRAK_CAV_STICKER (86): - Indicates driver has any FasTrak pass in - addition to the DMV issued Clean Air Vehicle - (CAV) sticker. - https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml - US_CO_EXPRESSTOLL (23): - CO, USA. - US_CO_GO_PASS (24): - CO, USA. - US_DE_EZPASSDE (25): - DE, USA. - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): - FL, USA. - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): - FL, USA. - US_FL_EPASS (67): - FL, USA. - US_FL_GIBA_TOLL_PASS (68): - FL, USA. - US_FL_LEEWAY (69): - FL, USA. - US_FL_SUNPASS (70): - FL, USA. - US_FL_SUNPASS_PRO (71): - FL, USA. - US_IL_EZPASSIL (73): - IL, USA. - US_IL_IPASS (72): - IL, USA. - US_IN_EZPASSIN (26): - IN, USA. - US_KS_BESTPASS_HORIZON (27): - KS, USA. - US_KS_KTAG (28): - KS, USA. - US_KS_NATIONALPASS (29): - KS, USA. - US_KS_PREPASS_ELITEPASS (30): - KS, USA. - US_KY_RIVERLINK (31): - KY, USA. - US_LA_GEAUXPASS (32): - LA, USA. - US_LA_TOLL_TAG (33): - LA, USA. - US_MA_EZPASSMA (6): - MA, USA. - US_MD_EZPASSMD (34): - MD, USA. - US_ME_EZPASSME (35): - ME, USA. - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): - MI, USA. - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): - MI, USA. - US_MI_IQ_PROX_CARD (38): - MI, USA. - US_MI_MACKINAC_BRIDGE_MAC_PASS (39): - MI, USA. - US_MI_NEXPRESS_TOLL (40): - MI, USA. - US_MN_EZPASSMN (41): - MN, USA. - US_NC_EZPASSNC (42): - NC, USA. - US_NC_PEACH_PASS (87): - NC, USA. - US_NC_QUICK_PASS (43): - NC, USA. - US_NH_EZPASSNH (80): - NH, USA. - US_NJ_DOWNBEACH_EXPRESS_PASS (75): - NJ, USA. - US_NJ_EZPASSNJ (74): - NJ, USA. - US_NY_EXPRESSPASS (76): - NY, USA. - US_NY_EZPASSNY (77): - NY, USA. - US_OH_EZPASSOH (44): - OH, USA. - US_PA_EZPASSPA (45): - PA, USA. - US_RI_EZPASSRI (46): - RI, USA. - US_SC_PALPASS (47): - SC, USA. - US_TX_BANCPASS (48): - TX, USA. - US_TX_DEL_RIO_PASS (49): - TX, USA. - US_TX_EFAST_PASS (50): - TX, USA. - US_TX_EAGLE_PASS_EXPRESS_CARD (51): - TX, USA. - US_TX_EPTOLL (52): - TX, USA. - US_TX_EZ_CROSS (53): - TX, USA. - US_TX_EZTAG (54): - TX, USA. - US_TX_LAREDO_TRADE_TAG (55): - TX, USA. - US_TX_PLUSPASS (56): - TX, USA. - US_TX_TOLLTAG (57): - TX, USA. - US_TX_TXTAG (58): - TX, USA. - US_TX_XPRESS_CARD (59): - TX, USA. - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): - UT, USA. - US_VA_EZPASSVA (61): - VA, USA. - US_WA_BREEZEBY (17): - WA, USA. - US_WA_GOOD_TO_GO (1): - WA, USA. - US_WV_EZPASSWV (62): - WV, USA. - US_WV_MEMORIAL_BRIDGE_TICKETS (63): - WV, USA. - US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): - WV, USA. - """ - TOLL_PASS_UNSPECIFIED = 0 - AU_ETOLL_TAG = 82 - AU_EWAY_TAG = 83 - AU_LINKT = 2 - AR_TELEPASE = 3 - BR_AUTO_EXPRESO = 81 - BR_CONECTCAR = 7 - BR_MOVE_MAIS = 8 - BR_PASSA_RAPIDO = 88 - BR_SEM_PARAR = 9 - BR_TAGGY = 10 - BR_VELOE = 11 - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 - CA_US_BLUE_WATER_EDGE_PASS = 18 - CA_US_CONNEXION = 19 - CA_US_NEXUS_CARD = 20 - ID_E_TOLL = 16 - IN_FASTAG = 78 - IN_LOCAL_HP_PLATE_EXEMPT = 79 - MX_IAVE = 90 - MX_PASE = 91 - MX_QUICKPASS = 93 - MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 - MX_TAG_IAVE = 12 - MX_TAG_TELEVIA = 13 - MX_TELEVIA = 92 - MX_VIAPASS = 14 - US_AL_FREEDOM_PASS = 21 - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 - US_CA_FASTRAK = 4 - US_CA_FASTRAK_CAV_STICKER = 86 - US_CO_EXPRESSTOLL = 23 - US_CO_GO_PASS = 24 - US_DE_EZPASSDE = 25 - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 - US_FL_EPASS = 67 - US_FL_GIBA_TOLL_PASS = 68 - US_FL_LEEWAY = 69 - US_FL_SUNPASS = 70 - US_FL_SUNPASS_PRO = 71 - US_IL_EZPASSIL = 73 - US_IL_IPASS = 72 - US_IN_EZPASSIN = 26 - US_KS_BESTPASS_HORIZON = 27 - US_KS_KTAG = 28 - US_KS_NATIONALPASS = 29 - US_KS_PREPASS_ELITEPASS = 30 - US_KY_RIVERLINK = 31 - US_LA_GEAUXPASS = 32 - US_LA_TOLL_TAG = 33 - US_MA_EZPASSMA = 6 - US_MD_EZPASSMD = 34 - US_ME_EZPASSME = 35 - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 - US_MI_IQ_PROX_CARD = 38 - US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 - US_MI_NEXPRESS_TOLL = 40 - US_MN_EZPASSMN = 41 - US_NC_EZPASSNC = 42 - US_NC_PEACH_PASS = 87 - US_NC_QUICK_PASS = 43 - US_NH_EZPASSNH = 80 - US_NJ_DOWNBEACH_EXPRESS_PASS = 75 - US_NJ_EZPASSNJ = 74 - US_NY_EXPRESSPASS = 76 - US_NY_EZPASSNY = 77 - US_OH_EZPASSOH = 44 - US_PA_EZPASSPA = 45 - US_RI_EZPASSRI = 46 - US_SC_PALPASS = 47 - US_TX_BANCPASS = 48 - US_TX_DEL_RIO_PASS = 49 - US_TX_EFAST_PASS = 50 - US_TX_EAGLE_PASS_EXPRESS_CARD = 51 - US_TX_EPTOLL = 52 - US_TX_EZ_CROSS = 53 - US_TX_EZTAG = 54 - US_TX_LAREDO_TRADE_TAG = 55 - US_TX_PLUSPASS = 56 - US_TX_TOLLTAG = 57 - US_TX_TXTAG = 58 - US_TX_XPRESS_CARD = 59 - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 - US_VA_EZPASSVA = 61 - US_WA_BREEZEBY = 17 - US_WA_GOOD_TO_GO = 1 - US_WV_EZPASSWV = 62 - US_WV_MEMORIAL_BRIDGE_TICKETS = 63 - US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py deleted file mode 100644 index 93cfaf1ee04c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Units', - }, -) - - -class Units(proto.Enum): - r"""A set of values that specify the unit of measure used in the - display. - - Values: - UNITS_UNSPECIFIED (0): - Units of measure not specified. Defaults to - the unit of measure inferred from the request. - METRIC (1): - Metric units of measure. - IMPERIAL (2): - Imperial (English) units of measure. - """ - UNITS_UNSPECIFIED = 0 - METRIC = 1 - IMPERIAL = 2 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py deleted file mode 100644 index a94a99025c80..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'VehicleEmissionType', - }, -) - - -class VehicleEmissionType(proto.Enum): - r"""A set of values describing the vehicle's emission type. - Applies only to the DRIVE travel mode. - - Values: - VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): - No emission type specified. Default to - GASOLINE. - GASOLINE (1): - Gasoline/petrol fueled vehicle. - ELECTRIC (2): - Electricity powered vehicle. - HYBRID (3): - Hybrid fuel (such as gasoline + electric) - vehicle. - DIESEL (4): - Diesel fueled vehicle. - """ - VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 - GASOLINE = 1 - ELECTRIC = 2 - HYBRID = 3 - DIESEL = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py deleted file mode 100644 index 2d71bb0a70a0..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import vehicle_emission_type - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'VehicleInfo', - }, -) - - -class VehicleInfo(proto.Message): - r"""Encapsulates the vehicle information, such as the license - plate last character. - - Attributes: - emission_type (google.maps.routing_v2.types.VehicleEmissionType): - Describes the vehicle's emission type. - Applies only to the DRIVE travel mode. - """ - - emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( - proto.ENUM, - number=2, - enum=vehicle_emission_type.VehicleEmissionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py deleted file mode 100644 index c25013cfd086..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import location as gmr_location - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Waypoint', - }, -) - - -class Waypoint(proto.Message): - r"""Encapsulates a waypoint. Waypoints mark both the beginning - and end of a route, and include intermediate stops along the - route. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - location (google.maps.routing_v2.types.Location): - A point specified using geographic - coordinates, including an optional heading. - - This field is a member of `oneof`_ ``location_type``. - place_id (str): - The POI Place ID associated with the - waypoint. - - This field is a member of `oneof`_ ``location_type``. - address (str): - Human readable address or a plus code. - See https://plus.codes for details. - - This field is a member of `oneof`_ ``location_type``. - via (bool): - Marks this waypoint as a milestone rather a stopping point. - For each non-via waypoint in the request, the response - appends an entry to the ``legs`` array to provide the - details for stopovers on that leg of the trip. Set this - value to true when you want the route to pass through this - waypoint without stopping over. Via waypoints don't cause an - entry to be added to the ``legs`` array, but they do route - the journey through the waypoint. You can only set this - value on waypoints that are intermediates. The request fails - if you set this field on terminal waypoints. If - ``ComputeRoutesRequest.optimize_waypoint_order`` is set to - true then this field cannot be set to true; otherwise, the - request fails. - vehicle_stopover (bool): - Indicates that the waypoint is meant for vehicles to stop - at, where the intention is to either pickup or drop-off. - When you set this value, the calculated route won't include - non-\ ``via`` waypoints on roads that are unsuitable for - pickup and drop-off. This option works only for ``DRIVE`` - and ``TWO_WHEELER`` travel modes, and when the - ``location_type`` is ``location``. - side_of_road (bool): - Indicates that the location of this waypoint is meant to - have a preference for the vehicle to stop at a particular - side of road. When you set this value, the route will pass - through the location so that the vehicle can stop at the - side of road that the location is biased towards from the - center of the road. This option works only for 'DRIVE' and - 'TWO_WHEELER' travel modes. - """ - - location: gmr_location.Location = proto.Field( - proto.MESSAGE, - number=1, - oneof='location_type', - message=gmr_location.Location, - ) - place_id: str = proto.Field( - proto.STRING, - number=2, - oneof='location_type', - ) - address: str = proto.Field( - proto.STRING, - number=7, - oneof='location_type', - ) - via: bool = proto.Field( - proto.BOOL, - number=3, - ) - vehicle_stopover: bool = proto.Field( - proto.BOOL, - number=4, - ) - side_of_road: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py deleted file mode 100644 index 59757e684c85..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/routing_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py deleted file mode 100644 index 381f53f7a26e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py deleted file mode 100644 index 125691404b0b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py deleted file mode 100644 index c978c3e55cd7..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py deleted file mode 100644 index ca13730e4ddc..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json deleted file mode 100644 index b5ed5aca319c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json +++ /dev/null @@ -1,321 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.routing.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-maps-routing", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_route_matrix_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_route_matrix_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_routes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_routes_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py deleted file mode 100644 index 291c4ea93db5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class routingCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'extra_computations', ), - 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'units', 'requested_reference_routes', 'extra_computations', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=routingCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the routing client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py deleted file mode 100644 index 1047dfef360b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-maps-routing' - - -description = "Google Maps Routing API client library" - -version = {} -with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-maps-routing" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.maps"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adfea7ee..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py deleted file mode 100644 index 55f7b3a4ba31..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py +++ /dev/null @@ -1,1750 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.maps.routing_v2.services.routes import RoutesAsyncClient -from google.maps.routing_v2.services.routes import RoutesClient -from google.maps.routing_v2.services.routes import transports -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routes_service -from google.maps.routing_v2.types import routing_preference -from google.maps.routing_v2.types import toll_passes -from google.maps.routing_v2.types import units -from google.maps.routing_v2.types import vehicle_emission_type -from google.maps.routing_v2.types import vehicle_info -from google.maps.routing_v2.types import waypoint -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -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 RoutesClient._get_default_mtls_endpoint(None) is None - assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RoutesGrpcTransport, "grpc"), - (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RoutesRestTransport, "rest"), -]) -def test_routes_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -def test_routes_client_get_transport_class(): - transport = RoutesClient.get_transport_class() - available_transports = [ - transports.RoutesGrpcTransport, - transports.RoutesRestTransport, - ] - assert transport in available_transports - - transport = RoutesClient.get_transport_class("grpc") - assert transport == transports.RoutesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -def test_routes_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RoutesClient, transports.RoutesRestTransport, "rest", "true"), - (RoutesClient, transports.RoutesRestTransport, "rest", "false"), -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_routes_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - RoutesClient, RoutesAsyncClient -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -def test_routes_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -def test_routes_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RoutesClient, transports.RoutesRestTransport, "rest", None), -]) -def test_routes_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_routes_client_client_options_from_dict(): - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RoutesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_routes_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "routes.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes(request_type, transport: str = 'grpc'): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = routes_service.ComputeRoutesResponse( - ) - response = client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - client.compute_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - -@pytest.mark.asyncio -async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( - )) - response = await client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -@pytest.mark.asyncio -async def test_compute_routes_async_from_dict(): - await test_compute_routes_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix(request_type, transport: str = 'grpc'): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([routes_service.RouteMatrixElement()]) - response = client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, routes_service.RouteMatrixElement) - - -def test_compute_route_matrix_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - client.compute_route_matrix() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - -@pytest.mark.asyncio -async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) - response = await client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, routes_service.RouteMatrixElement) - - -@pytest.mark.asyncio -async def test_compute_route_matrix_async_from_dict(): - await test_compute_route_matrix_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes_rest(request_type): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = routes_service.ComputeRoutesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.compute_routes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): - transport_class = transports.RoutesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.ComputeRoutesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.compute_routes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_routes_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_routes._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_routes_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) - - request = routes_service.ComputeRoutesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.ComputeRoutesResponse() - - client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compute_routes_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRoutesRequest): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.compute_routes(request) - - -def test_compute_routes_rest_error(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix_rest(request_type): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = routes_service.RouteMatrixElement( - origin_index=1279, - destination_index=1817, - condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, - distance_meters=1594, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - json_return_value = "[{}]".format(json_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.compute_route_matrix(request) - - assert isinstance(response, Iterable) - response = next(response) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.RouteMatrixElement) - assert response.origin_index == 1279 - assert response.destination_index == 1817 - assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS - assert response.distance_meters == 1594 - - -def test_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): - transport_class = transports.RoutesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.RouteMatrixElement() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - json_return_value = "[{}]".format(json_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.compute_route_matrix(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_route_matrix_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_route_matrix_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) - req.return_value._content = "[{}]".format(req.return_value._content) - - request = routes_service.ComputeRouteMatrixRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.RouteMatrixElement() - - client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compute_route_matrix_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.compute_route_matrix(request) - - -def test_compute_route_matrix_rest_error(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RoutesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RoutesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = RoutesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RoutesGrpcTransport, - ) - -def test_routes_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_routes_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'compute_routes', - 'compute_route_matrix', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_routes_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -def test_routes_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport() - adc.assert_called_once() - - -def test_routes_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - RoutesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - ], -) -def test_routes_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, - ], -) -def test_routes_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.RoutesGrpcTransport, grpc_helpers), - (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_routes_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "routes.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_routes_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.RoutesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_routes_host_no_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_routes_host_with_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_routes_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RoutesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RoutesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.compute_routes._session - session2 = client2.transport.compute_routes._session - assert session1 != session2 - session1 = client1.transport.compute_route_matrix._session - session2 = client2.transport.compute_route_matrix._session - assert session1 != session2 -def test_routes_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_routes_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - 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 - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - 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=cred, - credentials_file=None, - scopes=None, - 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 - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_transport_channel_mtls_with_adc( - transport_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), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - 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 - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RoutesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = RoutesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = RoutesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = RoutesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RoutesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = RoutesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = RoutesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = RoutesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RoutesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = RoutesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: - transport_class = RoutesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (RoutesClient, transports.RoutesGrpcTransport), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py index 36b93db88bf2..8324d3b000e0 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py @@ -101,7 +101,9 @@ class ComputeRoutesRequest(proto.Message): the request fails. compute_alternative_routes (bool): Optional. Specifies whether to calculate - alternate routes in addition to the route. + alternate routes in addition to the route. No + alternative routes are returned for requests + that have intermediate waypoints. route_modifiers (google.maps.routing_v2.types.RouteModifiers): Optional. A set of conditions to satisfy that affect the way routes are calculated. From 10ba5a544d1f7ef86c9e7c62e566fc5b8e66c678 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 17 Mar 2023 18:34:56 +0000 Subject: [PATCH 05/12] chore: Update gapic-generator-python to v1.9.0 PiperOrigin-RevId: 517425588 Source-Link: https://github.com/googleapis/googleapis/commit/33c93eb8b4d3aaf88e44a1be197811052be62282 Source-Link: https://github.com/googleapis/googleapis-gen/commit/d5f59789d19fc43270ff2124967d4ec8992b8e8f Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcm91dGluZy8uT3dsQm90LnlhbWwiLCJoIjoiZDVmNTk3ODlkMTlmYzQzMjcwZmYyMTI0OTY3ZDRlYzg5OTJiOGU4ZiJ9 --- .../google-maps-routing/v2/.coveragerc | 13 + .../google-maps-routing/v2/.flake8 | 33 + .../google-maps-routing/v2/MANIFEST.in | 2 + .../google-maps-routing/v2/README.rst | 49 + .../google-maps-routing/v2/docs/conf.py | 376 ++++ .../google-maps-routing/v2/docs/index.rst | 7 + .../v2/docs/routing_v2/routes.rst | 6 + .../v2/docs/routing_v2/services.rst | 6 + .../v2/docs/routing_v2/types.rst | 6 + .../v2/google/maps/routing/__init__.py | 97 + .../v2/google/maps/routing/gapic_version.py | 16 + .../v2/google/maps/routing/py.typed | 2 + .../v2/google/maps/routing_v2/__init__.py | 98 + .../maps/routing_v2/gapic_metadata.json | 58 + .../google/maps/routing_v2/gapic_version.py | 16 + .../v2/google/maps/routing_v2/py.typed | 2 + .../maps/routing_v2/services/__init__.py | 15 + .../routing_v2/services/routes/__init__.py | 22 + .../services/routes/async_client.py | 416 ++++ .../maps/routing_v2/services/routes/client.py | 613 ++++++ .../services/routes/transports/__init__.py | 38 + .../services/routes/transports/base.py | 161 ++ .../services/routes/transports/grpc.py | 363 ++++ .../routes/transports/grpc_asyncio.py | 362 ++++ .../services/routes/transports/rest.py | 417 ++++ .../google/maps/routing_v2/types/__init__.py | 105 + .../maps/routing_v2/types/fallback_info.py | 103 + .../routing_v2/types/geocoding_results.py | 125 ++ .../google/maps/routing_v2/types/location.py | 62 + .../google/maps/routing_v2/types/maneuver.py | 96 + .../types/navigation_instruction.py | 58 + .../google/maps/routing_v2/types/polyline.py | 113 ++ .../v2/google/maps/routing_v2/types/route.py | 409 ++++ .../maps/routing_v2/types/route_label.py | 57 + .../maps/routing_v2/types/route_modifiers.py | 97 + .../routing_v2/types/route_travel_mode.py | 59 + .../maps/routing_v2/types/routes_service.py | 512 +++++ .../routing_v2/types/routing_preference.py | 67 + .../types/speed_reading_interval.py | 89 + .../google/maps/routing_v2/types/toll_info.py | 56 + .../maps/routing_v2/types/toll_passes.py | 348 ++++ .../v2/google/maps/routing_v2/types/units.py | 49 + .../routing_v2/types/vehicle_emission_type.py | 56 + .../maps/routing_v2/types/vehicle_info.py | 50 + .../google/maps/routing_v2/types/waypoint.py | 123 ++ .../google-maps-routing/v2/mypy.ini | 3 + .../google-maps-routing/v2/noxfile.py | 184 ++ ...rated_routes_compute_route_matrix_async.py | 52 + ...erated_routes_compute_route_matrix_sync.py | 52 + ...2_generated_routes_compute_routes_async.py | 51 + ...v2_generated_routes_compute_routes_sync.py | 51 + ...ippet_metadata_google.maps.routing.v2.json | 321 +++ .../v2/scripts/fixup_routing_v2_keywords.py | 177 ++ .../google-maps-routing/v2/setup.py | 91 + .../v2/testing/constraints-3.10.txt | 7 + .../v2/testing/constraints-3.11.txt | 7 + .../v2/testing/constraints-3.12.txt | 7 + .../v2/testing/constraints-3.7.txt | 10 + .../v2/testing/constraints-3.8.txt | 7 + .../v2/testing/constraints-3.9.txt | 7 + .../google-maps-routing/v2/tests/__init__.py | 16 + .../v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/routing_v2/__init__.py | 16 + .../unit/gapic/routing_v2/test_routes.py | 1750 +++++++++++++++++ 65 files changed, 8669 insertions(+) create mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc create mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 create mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py create mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini create mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json create mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py create mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py diff --git a/owl-bot-staging/google-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc new file mode 100644 index 000000000000..d0ce5597b0a9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/routing/__init__.py + google/maps/routing/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.flake8 @@ -0,0 +1,33 @@ +# -*- 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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in new file mode 100644 index 000000000000..c5b56c111c00 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/routing *.py +recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst new file mode 100644 index 000000000000..f0002366e552 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Routing API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Maps Routing API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py new file mode 100644 index 000000000000..d7a10abed96b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-maps-routing documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +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"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-maps-routing" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# 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"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# 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 + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +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 = { + "description": "Google Maps Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# 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 + +# 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 + +# 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, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# 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 = [] + +# 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' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is 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 = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# 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' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# 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' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-maps-routing-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- 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', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-maps-routing.tex", + u"google-maps-routing 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 + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# 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 = [ + ( + root_doc, + "google-maps-routing", + u"Google Maps Routing Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-maps-routing", + u"google-maps-routing Documentation", + author, + "google-maps-routing", + "GAPIC library for Google Maps Routing API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# 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), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst new file mode 100644 index 000000000000..e2563dd88ee9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + routing_v2/services + routing_v2/types diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst new file mode 100644 index 000000000000..3d52309cddae --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst @@ -0,0 +1,6 @@ +Routes +------------------------ + +.. automodule:: google.maps.routing_v2.services.routes + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst new file mode 100644 index 000000000000..e96568dc434c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst @@ -0,0 +1,6 @@ +Services for Google Maps Routing v2 API +======================================= +.. toctree:: + :maxdepth: 2 + + routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst new file mode 100644 index 000000000000..176a5a812cf8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst @@ -0,0 +1,6 @@ +Types for Google Maps Routing v2 API +==================================== + +.. automodule:: google.maps.routing_v2.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py new file mode 100644 index 000000000000..59020a3484c3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.maps.routing import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.routing_v2.services.routes.client import RoutesClient +from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient + +from google.maps.routing_v2.types.fallback_info import FallbackInfo +from google.maps.routing_v2.types.fallback_info import FallbackReason +from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode +from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint +from google.maps.routing_v2.types.geocoding_results import GeocodingResults +from google.maps.routing_v2.types.location import Location +from google.maps.routing_v2.types.maneuver import Maneuver +from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction +from google.maps.routing_v2.types.polyline import Polyline +from google.maps.routing_v2.types.polyline import PolylineEncoding +from google.maps.routing_v2.types.polyline import PolylineQuality +from google.maps.routing_v2.types.route import Route +from google.maps.routing_v2.types.route import RouteLeg +from google.maps.routing_v2.types.route import RouteLegStep +from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory +from google.maps.routing_v2.types.route import RouteLegTravelAdvisory +from google.maps.routing_v2.types.route import RouteTravelAdvisory +from google.maps.routing_v2.types.route_label import RouteLabel +from google.maps.routing_v2.types.route_modifiers import RouteModifiers +from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode +from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse +from google.maps.routing_v2.types.routes_service import RouteMatrixDestination +from google.maps.routing_v2.types.routes_service import RouteMatrixElement +from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin +from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition +from google.maps.routing_v2.types.routing_preference import RoutingPreference +from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval +from google.maps.routing_v2.types.toll_info import TollInfo +from google.maps.routing_v2.types.toll_passes import TollPass +from google.maps.routing_v2.types.units import Units +from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType +from google.maps.routing_v2.types.vehicle_info import VehicleInfo +from google.maps.routing_v2.types.waypoint import Waypoint + +__all__ = ('RoutesClient', + 'RoutesAsyncClient', + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py new file mode 100644 index 000000000000..405b1cebcf15 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py new file mode 100644 index 000000000000..cd9d694f63c6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.maps.routing_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.routes import RoutesClient +from .services.routes import RoutesAsyncClient + +from .types.fallback_info import FallbackInfo +from .types.fallback_info import FallbackReason +from .types.fallback_info import FallbackRoutingMode +from .types.geocoding_results import GeocodedWaypoint +from .types.geocoding_results import GeocodingResults +from .types.location import Location +from .types.maneuver import Maneuver +from .types.navigation_instruction import NavigationInstruction +from .types.polyline import Polyline +from .types.polyline import PolylineEncoding +from .types.polyline import PolylineQuality +from .types.route import Route +from .types.route import RouteLeg +from .types.route import RouteLegStep +from .types.route import RouteLegStepTravelAdvisory +from .types.route import RouteLegTravelAdvisory +from .types.route import RouteTravelAdvisory +from .types.route_label import RouteLabel +from .types.route_modifiers import RouteModifiers +from .types.route_travel_mode import RouteTravelMode +from .types.routes_service import ComputeRouteMatrixRequest +from .types.routes_service import ComputeRoutesRequest +from .types.routes_service import ComputeRoutesResponse +from .types.routes_service import RouteMatrixDestination +from .types.routes_service import RouteMatrixElement +from .types.routes_service import RouteMatrixOrigin +from .types.routes_service import RouteMatrixElementCondition +from .types.routing_preference import RoutingPreference +from .types.speed_reading_interval import SpeedReadingInterval +from .types.toll_info import TollInfo +from .types.toll_passes import TollPass +from .types.units import Units +from .types.vehicle_emission_type import VehicleEmissionType +from .types.vehicle_info import VehicleInfo +from .types.waypoint import Waypoint + +__all__ = ( + 'RoutesAsyncClient', +'ComputeRouteMatrixRequest', +'ComputeRoutesRequest', +'ComputeRoutesResponse', +'FallbackInfo', +'FallbackReason', +'FallbackRoutingMode', +'GeocodedWaypoint', +'GeocodingResults', +'Location', +'Maneuver', +'NavigationInstruction', +'Polyline', +'PolylineEncoding', +'PolylineQuality', +'Route', +'RouteLabel', +'RouteLeg', +'RouteLegStep', +'RouteLegStepTravelAdvisory', +'RouteLegTravelAdvisory', +'RouteMatrixDestination', +'RouteMatrixElement', +'RouteMatrixElementCondition', +'RouteMatrixOrigin', +'RouteModifiers', +'RouteTravelAdvisory', +'RouteTravelMode', +'RoutesClient', +'RoutingPreference', +'SpeedReadingInterval', +'TollInfo', +'TollPass', +'Units', +'VehicleEmissionType', +'VehicleInfo', +'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json new file mode 100644 index 000000000000..8382cea1d39a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json @@ -0,0 +1,58 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.routing_v2", + "protoPackage": "google.maps.routing.v2", + "schema": "1.0", + "services": { + "Routes": { + "clients": { + "grpc": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RoutesAsyncClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "rest": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py new file mode 100644 index 000000000000..405b1cebcf15 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py new file mode 100644 index 000000000000..e8e1c3845db5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py new file mode 100644 index 000000000000..ff3f8f71863f --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RoutesClient +from .async_client import RoutesAsyncClient + +__all__ = ( + 'RoutesClient', + 'RoutesAsyncClient', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py new file mode 100644 index 000000000000..7f8df74a140b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union + +from google.maps.routing_v2 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .client import RoutesClient + + +class RoutesAsyncClient: + """The Routes API.""" + + _client: RoutesClient + + DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RoutesClient.common_folder_path) + parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) + common_organization_path = staticmethod(RoutesClient.common_organization_path) + parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) + common_project_path = staticmethod(RoutesClient.common_project_path) + parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) + common_location_path = staticmethod(RoutesClient.common_location_path) + parse_common_location_path = staticmethod(RoutesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(RoutesClient).get_transport_class, type(RoutesClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RoutesTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RoutesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RoutesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # Create or coerce a protobuf request object. + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compute_routes, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + # Create or coerce a protobuf request object. + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compute_route_matrix, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RoutesAsyncClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py new file mode 100644 index 000000000000..1943383c7246 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py @@ -0,0 +1,613 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast + +from google.maps.routing_v2 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RoutesGrpcTransport +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .transports.rest import RoutesRestTransport + + +class RoutesClientMeta(type): + """Metaclass for the Routes client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] + _transport_registry["grpc"] = RoutesGrpcTransport + _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport + _transport_registry["rest"] = RoutesRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RoutesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RoutesClient(metaclass=RoutesClientMeta): + """The Routes API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "routes.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RoutesTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, RoutesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RoutesTransport): + # transport is a RoutesTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a routes_service.ComputeRoutesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, routes_service.ComputeRoutesRequest): + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_routes] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[routes_service.RouteMatrixElement]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.maps.routing_v2.types.RouteMatrixElement]: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a routes_service.ComputeRouteMatrixRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, routes_service.ComputeRouteMatrixRequest): + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RoutesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RoutesClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py new file mode 100644 index 000000000000..a15967f001c9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RoutesTransport +from .grpc import RoutesGrpcTransport +from .grpc_asyncio import RoutesGrpcAsyncIOTransport +from .rest import RoutesRestTransport +from .rest import RoutesRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] +_transport_registry['grpc'] = RoutesGrpcTransport +_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport +_transport_registry['rest'] = RoutesRestTransport + +__all__ = ( + 'RoutesTransport', + 'RoutesGrpcTransport', + 'RoutesGrpcAsyncIOTransport', + 'RoutesRestTransport', + 'RoutesRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py new file mode 100644 index 000000000000..a6fa68993eca --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.maps.routing_v2 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.maps.routing_v2.types import routes_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class RoutesTransport(abc.ABC): + """Abstract transport class for Routes.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'routes.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.compute_routes: gapic_v1.method.wrap_method( + self.compute_routes, + default_timeout=None, + client_info=client_info, + ), + self.compute_route_matrix: gapic_v1.method.wrap_method( + self.compute_route_matrix, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Union[ + routes_service.ComputeRoutesResponse, + Awaitable[routes_service.ComputeRoutesResponse] + ]]: + raise NotImplementedError() + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Union[ + routes_service.RouteMatrixElement, + Awaitable[routes_service.RouteMatrixElement] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RoutesTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py new file mode 100644 index 000000000000..8316c8b03587 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py @@ -0,0 +1,363 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO + + +class RoutesGrpcTransport(RoutesTransport): + """gRPC backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + ~.ComputeRoutesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self.grpc_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + ~.RouteMatrixElement]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RoutesGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py new file mode 100644 index 000000000000..752c5eaefc33 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO +from .grpc import RoutesGrpcTransport + + +class RoutesGrpcAsyncIOTransport(RoutesTransport): + """gRPC AsyncIO backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Awaitable[routes_service.ComputeRoutesResponse]]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + Awaitable[~.ComputeRoutesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self.grpc_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Awaitable[routes_service.RouteMatrixElement]]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + Awaitable[~.RouteMatrixElement]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'RoutesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py new file mode 100644 index 000000000000..c7fdf524b0c7 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.maps.routing_v2.types import routes_service + +from .base import RoutesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RoutesRestInterceptor: + """Interceptor for Routes. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RoutesRestTransport. + + .. code-block:: python + class MyCustomRoutesInterceptor(RoutesRestInterceptor): + def pre_compute_route_matrix(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_route_matrix(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_compute_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_routes(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) + client = RoutesClient(transport=transport) + + + """ + def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: + """Post-rpc interceptor for compute_routes + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RoutesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RoutesRestInterceptor + + +class RoutesRestTransport(RoutesTransport): + """REST backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[RoutesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RoutesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ComputeRouteMatrix(RoutesRestStub): + def __hash__(self): + return hash("ComputeRouteMatrix") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: routes_service.ComputeRouteMatrixRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + r"""Call the compute route matrix method over HTTP. + + Args: + request (~.routes_service.ComputeRouteMatrixRequest): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.routes_service.RouteMatrixElement: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/distanceMatrix/v2:computeRouteMatrix', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) + pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) + resp = self._interceptor.post_compute_route_matrix(resp) + return resp + + class _ComputeRoutes(RoutesRestStub): + def __hash__(self): + return hash("ComputeRoutes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: routes_service.ComputeRoutesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> routes_service.ComputeRoutesResponse: + r"""Call the compute routes method over HTTP. + + Args: + request (~.routes_service.ComputeRoutesRequest): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.routes_service.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/directions/v2:computeRoutes', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_compute_routes(request, metadata) + pb_request = routes_service.ComputeRoutesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = routes_service.ComputeRoutesResponse() + pb_resp = routes_service.ComputeRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_compute_routes(resp) + return resp + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RoutesRestTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py new file mode 100644 index 000000000000..7323899cfc30 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .fallback_info import ( + FallbackInfo, + FallbackReason, + FallbackRoutingMode, +) +from .geocoding_results import ( + GeocodedWaypoint, + GeocodingResults, +) +from .location import ( + Location, +) +from .navigation_instruction import ( + NavigationInstruction, +) +from .polyline import ( + Polyline, + PolylineEncoding, + PolylineQuality, +) +from .route import ( + Route, + RouteLeg, + RouteLegStep, + RouteLegStepTravelAdvisory, + RouteLegTravelAdvisory, + RouteTravelAdvisory, +) +from .route_modifiers import ( + RouteModifiers, +) +from .routes_service import ( + ComputeRouteMatrixRequest, + ComputeRoutesRequest, + ComputeRoutesResponse, + RouteMatrixDestination, + RouteMatrixElement, + RouteMatrixOrigin, + RouteMatrixElementCondition, +) +from .speed_reading_interval import ( + SpeedReadingInterval, +) +from .toll_info import ( + TollInfo, +) +from .vehicle_info import ( + VehicleInfo, +) +from .waypoint import ( + Waypoint, +) + +__all__ = ( + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py new file mode 100644 index 000000000000..99670aafac25 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'FallbackReason', + 'FallbackRoutingMode', + 'FallbackInfo', + }, +) + + +class FallbackReason(proto.Enum): + r"""Reasons for using fallback response. + + Values: + FALLBACK_REASON_UNSPECIFIED (0): + No fallback reason specified. + SERVER_ERROR (1): + A server error happened while calculating + routes with your preferred routing mode, but we + were able to return a result calculated by an + alternative mode. + LATENCY_EXCEEDED (2): + We were not able to finish the calculation + with your preferred routing mode on time, but we + were able to return a result calculated by an + alternative mode. + """ + FALLBACK_REASON_UNSPECIFIED = 0 + SERVER_ERROR = 1 + LATENCY_EXCEEDED = 2 + + +class FallbackRoutingMode(proto.Enum): + r"""Actual routing mode used for returned fallback response. + + Values: + FALLBACK_ROUTING_MODE_UNSPECIFIED (0): + Not used. + FALLBACK_TRAFFIC_UNAWARE (1): + Indicates the "TRAFFIC_UNAWARE" routing mode was used to + compute the response. + FALLBACK_TRAFFIC_AWARE (2): + Indicates the "TRAFFIC_AWARE" routing mode was used to + compute the response. + """ + FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 + FALLBACK_TRAFFIC_UNAWARE = 1 + FALLBACK_TRAFFIC_AWARE = 2 + + +class FallbackInfo(proto.Message): + r"""Information related to how and why a fallback result was + used. If this field is set, then it means the server used a + different routing mode from your preferred mode as fallback. + + Attributes: + routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): + Routing mode used for the response. If + fallback was triggered, the mode may be + different from routing preference set in the + original client request. + reason (google.maps.routing_v2.types.FallbackReason): + The reason why fallback response was used + instead of the original response. This field is + only populated when the fallback mode is + triggered and the fallback response is returned. + """ + + routing_mode: 'FallbackRoutingMode' = proto.Field( + proto.ENUM, + number=1, + enum='FallbackRoutingMode', + ) + reason: 'FallbackReason' = proto.Field( + proto.ENUM, + number=2, + enum='FallbackReason', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py new file mode 100644 index 000000000000..ffa385a59a75 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'GeocodingResults', + 'GeocodedWaypoint', + }, +) + + +class GeocodingResults(proto.Message): + r"""Contains GeocodedWaypoints for origin, destination and + intermediate waypoints. Only populated for address waypoints. + + Attributes: + origin (google.maps.routing_v2.types.GeocodedWaypoint): + Origin geocoded waypoint. + destination (google.maps.routing_v2.types.GeocodedWaypoint): + Destination geocoded waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.GeocodedWaypoint]): + A list of intermediate geocoded waypoints + each containing an index field that corresponds + to the zero-based position of the waypoint in + the order they were specified in the request. + """ + + origin: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=1, + message='GeocodedWaypoint', + ) + destination: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=2, + message='GeocodedWaypoint', + ) + intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='GeocodedWaypoint', + ) + + +class GeocodedWaypoint(proto.Message): + r"""Details about the locations used as waypoints. Only populated + for address waypoints. Includes details about the geocoding + results for the purposes of determining what the address was + geocoded to. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + geocoder_status (google.rpc.status_pb2.Status): + Indicates the status code resulting from the + geocoding operation. + intermediate_waypoint_request_index (int): + The index of the corresponding intermediate + waypoint in the request. Only populated if the + corresponding waypoint is an intermediate + waypoint. + + This field is a member of `oneof`_ ``_intermediate_waypoint_request_index``. + type_ (MutableSequence[str]): + The type(s) of the result, in the form of + zero or more type tags. Supported types: + https://developers.google.com/maps/documentation/geocoding/requests-geocoding#Types + partial_match (bool): + Indicates that the geocoder did not return an + exact match for the original request, though it + was able to match part of the requested address. + You may wish to examine the original request for + misspellings and/or an incomplete address. + place_id (str): + The place ID for this result. + """ + + geocoder_status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + intermediate_waypoint_request_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + type_: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + partial_match: bool = proto.Field( + proto.BOOL, + number=4, + ) + place_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py new file mode 100644 index 000000000000..722cd7dda46a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Location', + }, +) + + +class Location(proto.Message): + r"""Encapsulates a location (a geographic point, and an optional + heading). + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + The waypoint's geographic coordinates. + heading (google.protobuf.wrappers_pb2.Int32Value): + The compass heading associated with the direction of the + flow of traffic. This value is used to specify the side of + the road to use for pickup and drop-off. Heading values can + be from 0 to 360, where 0 specifies a heading of due North, + 90 specifies a heading of due East, etc. You can use this + field only for ``DRIVE`` and ``TWO_WHEELER`` travel modes. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + heading: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py new file mode 100644 index 000000000000..60e5cd3cb9c6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Maneuver', + }, +) + + +class Maneuver(proto.Enum): + r"""A set of values that specify the navigation action to take + for the current step (e.g., turn left, merge, straight, etc.). + + Values: + MANEUVER_UNSPECIFIED (0): + Not used. + TURN_SLIGHT_LEFT (1): + Turn slightly to the left. + TURN_SHARP_LEFT (2): + Turn sharply to the left. + UTURN_LEFT (3): + Make a left u-turn. + TURN_LEFT (4): + Turn left. + TURN_SLIGHT_RIGHT (5): + Turn slightly to the right. + TURN_SHARP_RIGHT (6): + Turn sharply to the right. + UTURN_RIGHT (7): + Make a right u-turn. + TURN_RIGHT (8): + Turn right. + STRAIGHT (9): + Go straight. + RAMP_LEFT (10): + Take the left ramp. + RAMP_RIGHT (11): + Take the right ramp. + MERGE (12): + Merge into traffic. + FORK_LEFT (13): + Take the left fork. + FORK_RIGHT (14): + Take the right fork. + FERRY (15): + Take the ferry. + FERRY_TRAIN (16): + Take the train leading onto the ferry. + ROUNDABOUT_LEFT (17): + Turn left at the roundabout. + ROUNDABOUT_RIGHT (18): + Turn right at the roundabout. + """ + MANEUVER_UNSPECIFIED = 0 + TURN_SLIGHT_LEFT = 1 + TURN_SHARP_LEFT = 2 + UTURN_LEFT = 3 + TURN_LEFT = 4 + TURN_SLIGHT_RIGHT = 5 + TURN_SHARP_RIGHT = 6 + UTURN_RIGHT = 7 + TURN_RIGHT = 8 + STRAIGHT = 9 + RAMP_LEFT = 10 + RAMP_RIGHT = 11 + MERGE = 12 + FORK_LEFT = 13 + FORK_RIGHT = 14 + FERRY = 15 + FERRY_TRAIN = 16 + ROUNDABOUT_LEFT = 17 + ROUNDABOUT_RIGHT = 18 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py new file mode 100644 index 000000000000..dc8b69e76ccd --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import maneuver as gmr_maneuver + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'NavigationInstruction', + }, +) + + +class NavigationInstruction(proto.Message): + r"""Encapsulates navigation instructions for a + [RouteLegStep][google.maps.routing.v2.RouteLegStep] + + Attributes: + maneuver (google.maps.routing_v2.types.Maneuver): + Encapsulates the navigation instructions for + the current step (e.g., turn left, merge, + straight, etc.). This field determines which + icon to display. + instructions (str): + Instructions for navigating this step. + """ + + maneuver: gmr_maneuver.Maneuver = proto.Field( + proto.ENUM, + number=1, + enum=gmr_maneuver.Maneuver, + ) + instructions: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py new file mode 100644 index 000000000000..4d9630691288 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'PolylineQuality', + 'PolylineEncoding', + 'Polyline', + }, +) + + +class PolylineQuality(proto.Enum): + r"""A set of values that specify the quality of the polyline. + + Values: + POLYLINE_QUALITY_UNSPECIFIED (0): + No polyline quality preference specified. Defaults to + ``OVERVIEW``. + HIGH_QUALITY (1): + Specifies a high-quality polyline - which is composed using + more points than ``OVERVIEW``, at the cost of increased + response size. Use this value when you need more precision. + OVERVIEW (2): + Specifies an overview polyline - which is composed using a + small number of points. Use this value when displaying an + overview of the route. Using this option has a lower request + latency compared to using the ``HIGH_QUALITY`` option. + """ + POLYLINE_QUALITY_UNSPECIFIED = 0 + HIGH_QUALITY = 1 + OVERVIEW = 2 + + +class PolylineEncoding(proto.Enum): + r"""Specifies the preferred type of polyline to be returned. + + Values: + POLYLINE_ENCODING_UNSPECIFIED (0): + No polyline type preference specified. Defaults to + ``ENCODED_POLYLINE``. + ENCODED_POLYLINE (1): + Specifies a polyline encoded using the `polyline encoding + algorithm `__. + GEO_JSON_LINESTRING (2): + Specifies a polyline using the `GeoJSON LineString + format `__ + """ + POLYLINE_ENCODING_UNSPECIFIED = 0 + ENCODED_POLYLINE = 1 + GEO_JSON_LINESTRING = 2 + + +class Polyline(proto.Message): + r"""Encapsulates an encoded polyline. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + encoded_polyline (str): + The string encoding of the polyline using the `polyline + encoding + algorithm `__ + + This field is a member of `oneof`_ ``polyline_type``. + geo_json_linestring (google.protobuf.struct_pb2.Struct): + Specifies a polyline using the `GeoJSON LineString + format `__ + + This field is a member of `oneof`_ ``polyline_type``. + """ + + encoded_polyline: str = proto.Field( + proto.STRING, + number=1, + oneof='polyline_type', + ) + geo_json_linestring: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + oneof='polyline_type', + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py new file mode 100644 index 000000000000..2a57054febff --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py @@ -0,0 +1,409 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.geo.type import viewport_pb2 # type: ignore +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction +from google.maps.routing_v2.types import polyline as gmr_polyline +from google.maps.routing_v2.types import route_label +from google.maps.routing_v2.types import speed_reading_interval +from google.maps.routing_v2.types import toll_info as gmr_toll_info +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Route', + 'RouteTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteLegStepTravelAdvisory', + 'RouteLeg', + 'RouteLegStep', + }, +) + + +class Route(proto.Message): + r"""Encapsulates a route, which consists of a series of connected + road segments that join beginning, ending, and intermediate + waypoints. + + Attributes: + route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): + Labels for the ``Route`` that are useful to identify + specific properties of the route to compare against others. + legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): + A collection of legs (path segments between waypoints) that + make-up the route. Each leg corresponds to the trip between + two non-\ ``via`` Waypoints. For example, a route with no + intermediate waypoints has only one leg. A route that + includes one non-\ ``via`` intermediate waypoint has two + legs. A route that includes one ``via`` intermediate + waypoint has one leg. The order of the legs matches the + order of Waypoints from ``origin`` to ``intermediates`` to + ``destination``. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this + value is the same as ``static_duration``. If you set the + ``routing_preference`` to either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the route + without taking traffic conditions into + consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall route polyline. This polyline will be the + combined polyline of all ``legs``. + description (str): + A description of the route. + warnings (MutableSequence[str]): + An array of warnings to show when displaying + the route. + viewport (google.geo.type.viewport_pb2.Viewport): + The viewport bounding box of the polyline. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. + route_token (str): + Web-safe base64 encoded route token that can be passed to + NavigationSDK, which allows the Navigation SDK to + reconstruct the route during navigation, and in the event of + rerouting honor the original intention when Routes + ComputeRoutes is called. Customers should treat this token + as an opaque blob. NOTE: ``Route.route_token`` is only + available for requests that have set + ``ComputeRoutesRequest.routing_preference`` to + ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. + ``Route.route_token`` is also not supported for requests + that have Via waypoints. + """ + + route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( + proto.ENUM, + number=13, + enum=route_label.RouteLabel, + ) + legs: MutableSequence['RouteLeg'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteLeg', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=2, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_polyline.Polyline, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + warnings: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + viewport: viewport_pb2.Viewport = proto.Field( + proto.MESSAGE, + number=8, + message=viewport_pb2.Viewport, + ) + travel_advisory: 'RouteTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=9, + message='RouteTravelAdvisory', + ) + route_token: str = proto.Field( + proto.STRING, + number=12, + ) + + +class RouteTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction + etc. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Encapsulates information about tolls on the Route. This + field is only populated if we expect there are tolls on the + Route. If this field is set but the estimated_price subfield + is not populated, we expect that road contains tolls but we + do not know an estimated price. If this field is not set, + then we expect there is no toll on the Route. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the route without overlap. The + start point of a specified interval is the same as the end + point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + fuel_consumption_microliters (int): + The fuel consumption prediction in + microliters. + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=speed_reading_interval.SpeedReadingInterval, + ) + fuel_consumption_microliters: int = proto.Field( + proto.INT64, + number=5, + ) + + +class RouteLegTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction + etc. on a route leg. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Encapsulates information about tolls on the specific + RouteLeg. This field is only populated if we expect there + are tolls on the RouteLeg. If this field is set but the + estimated_price subfield is not populated, we expect that + road contains tolls but we do not know an estimated price. + If this field does not exist, then there is no toll on the + RouteLeg. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the RouteLg without overlap. + The start point of a specified interval is the same as the + end point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLegStepTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction on + a leg step. + + Attributes: + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + NOTE: This field is not currently populated. + """ + + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLeg(proto.Message): + r"""Encapsulates a segment between non-\ ``via`` waypoints. + + Attributes: + distance_meters (int): + The travel distance of the route leg, in + meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the leg. If the + ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then + this value is the same as ``static_duration``. If the + ``route_preference`` is either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the leg, + calculated without taking traffic conditions + into consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall polyline for this leg. This includes that each + ``step``'s polyline. + start_location (google.maps.routing_v2.types.Location): + The start location of this leg. This might be different from + the provided ``origin``. For example, when the provided + ``origin`` is not near a road, this is a point on the road. + end_location (google.maps.routing_v2.types.Location): + The end location of this leg. This might be different from + the provided ``destination``. For example, when the provided + ``destination`` is not near a road, this is a point on the + road. + steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): + An array of steps denoting segments within + this leg. Each step represents one navigation + instruction. + travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): + Encapsulates the additional information that + the user should be informed about, such as + possible traffic zone restriction etc. on a + route leg. + """ + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=4, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=6, + message=location.Location, + ) + steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='RouteLegStep', + ) + travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=8, + message='RouteLegTravelAdvisory', + ) + + +class RouteLegStep(proto.Message): + r"""Encapsulates a segment of a ``RouteLeg``. A step corresponds to a + single navigation instruction. Route legs are made up of steps. + + Attributes: + distance_meters (int): + The travel distance of this step, in meters. + In some circumstances, this field might not have + a value. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of travel through this step + without taking traffic conditions into + consideration. In some circumstances, this field + might not have a value. + polyline (google.maps.routing_v2.types.Polyline): + The polyline associated with this step. + start_location (google.maps.routing_v2.types.Location): + The start location of this step. + end_location (google.maps.routing_v2.types.Location): + The end location of this step. + navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): + Navigation instructions. + travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): + Encapsulates the additional information that + the user should be informed about, such as + possible traffic zone restriction on a leg step. + """ + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=4, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( + proto.MESSAGE, + number=6, + message=gmr_navigation_instruction.NavigationInstruction, + ) + travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=7, + message='RouteLegStepTravelAdvisory', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py new file mode 100644 index 000000000000..a3e095209d58 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteLabel', + }, +) + + +class RouteLabel(proto.Enum): + r"""Labels for the ``Route`` that are useful to identify specific + properties of the route to compare against others. + + Values: + ROUTE_LABEL_UNSPECIFIED (0): + Default - not used. + DEFAULT_ROUTE (1): + The default "best" route returned for the + route computation. + DEFAULT_ROUTE_ALTERNATE (2): + An alternative to the default "best" route. Routes like this + will be returned when + ``ComputeRoutesRequest.compute_alternative_routes`` is + specified. + FUEL_EFFICIENT (3): + Fuel efficient route. Routes labeled with + this value are determined to be optimized for + Eco parameters such as fuel consumption. + """ + ROUTE_LABEL_UNSPECIFIED = 0 + DEFAULT_ROUTE = 1 + DEFAULT_ROUTE_ALTERNATE = 2 + FUEL_EFFICIENT = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py new file mode 100644 index 000000000000..59f5e6420c4c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import toll_passes as gmr_toll_passes +from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteModifiers', + }, +) + + +class RouteModifiers(proto.Message): + r"""Encapsulates a set of optional conditions to satisfy when + calculating the routes. + + Attributes: + avoid_tolls (bool): + Specifies whether to avoid toll roads where reasonable. + Preference will be given to routes not containing toll + roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` + travel modes. + avoid_highways (bool): + Specifies whether to avoid highways where reasonable. + Preference will be given to routes not containing highways. + Applies only to the ``DRIVE`` and ``TWO_WHEELER`` travel + modes. + avoid_ferries (bool): + Specifies whether to avoid ferries where reasonable. + Preference will be given to routes not containing travel by + ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` + travel modes. + avoid_indoor (bool): + Specifies whether to avoid navigating indoors where + reasonable. Preference will be given to routes not + containing indoor navigation. Applies only to the ``WALK`` + travel mode. + vehicle_info (google.maps.routing_v2.types.VehicleInfo): + Specifies the vehicle information. + toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): + Encapsulates information about toll passes. If toll passes + are provided, the API tries to return the pass price. If + toll passes are not provided, the API treats the toll pass + as unknown and tries to return the cash price. Applies only + to the DRIVE and TWO_WHEELER travel modes. + """ + + avoid_tolls: bool = proto.Field( + proto.BOOL, + number=1, + ) + avoid_highways: bool = proto.Field( + proto.BOOL, + number=2, + ) + avoid_ferries: bool = proto.Field( + proto.BOOL, + number=3, + ) + avoid_indoor: bool = proto.Field( + proto.BOOL, + number=4, + ) + vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_vehicle_info.VehicleInfo, + ) + toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( + proto.ENUM, + number=6, + enum=gmr_toll_passes.TollPass, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py new file mode 100644 index 000000000000..14d466006fae --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteTravelMode', + }, +) + + +class RouteTravelMode(proto.Enum): + r"""A set of values used to specify the mode of travel. NOTE: WALK, + BICYCLE, and TWO_WHEELER routes are in beta and might sometimes be + missing clear sidewalks, pedestrian paths, or bicycling paths. You + must display this warning to the user for all walking, bicycling, + and two-wheel routes that you display in your app. + + Values: + TRAVEL_MODE_UNSPECIFIED (0): + No travel mode specified. Defaults to ``DRIVE``. + DRIVE (1): + Travel by passenger car. + BICYCLE (2): + Travel by bicycle. + WALK (3): + Travel by walking. + TWO_WHEELER (4): + Two-wheeled, motorized vehicle. For example, motorcycle. + Note that this differs from the ``BICYCLE`` travel mode + which covers human-powered mode. + """ + TRAVEL_MODE_UNSPECIFIED = 0 + DRIVE = 1 + BICYCLE = 2 + WALK = 3 + TWO_WHEELER = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py new file mode 100644 index 000000000000..dffc427d20a5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import fallback_info as gmr_fallback_info +from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routing_preference as gmr_routing_preference +from google.maps.routing_v2.types import units as gmr_units +from google.maps.routing_v2.types import waypoint as gmr_waypoint +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteMatrixElementCondition', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'ComputeRouteMatrixRequest', + 'RouteMatrixOrigin', + 'RouteMatrixDestination', + 'RouteMatrixElement', + }, +) + + +class RouteMatrixElementCondition(proto.Enum): + r"""The condition of the route being returned. + + Values: + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): + Only used when the ``status`` of the element is not OK. + ROUTE_EXISTS (1): + A route was found, and the corresponding + information was filled out for the element. + ROUTE_NOT_FOUND (2): + No route could be found. Fields containing route + information, such as ``distance_meters`` or ``duration``, + will not be filled out in the element. + """ + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 + ROUTE_EXISTS = 1 + ROUTE_NOT_FOUND = 2 + + +class ComputeRoutesRequest(proto.Message): + r"""ComputeRoutes request message. + + Attributes: + origin (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint. + destination (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): + Optional. A set of waypoints along the route + (excluding terminal points), for either stopping + at or passing by. Up to 25 intermediate + waypoints are supported. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, then an error is returned. You can + specify this option only when the ``travel_mode`` is + ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. + polyline_quality (google.maps.routing_v2.types.PolylineQuality): + Optional. Specifies your preference for the + quality of the polyline. + polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): + Optional. Specifies the preferred encoding + for the polyline. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't + set this value, then this value defaults to the + time that you made the request. If you set this + value to a time that has already occurred, then + the request fails. + compute_alternative_routes (bool): + Optional. Specifies whether to calculate + alternate routes in addition to the route. No + alternative routes are returned for requests + that have intermediate waypoints. + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. A set of conditions to satisfy that + affect the way routes are calculated. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + See `Language + Support `__ + for the list of supported languages. When you don't provide + this value, the display language is inferred from the + location of the route request. + units (google.maps.routing_v2.types.Units): + Optional. Specifies the units of measure for the display + fields. This includes the ``instruction`` field in + ``NavigationInstruction``. The units of measure used for the + route, leg, step distance, and duration are not affected by + this value. If you don't provide this value, then the + display units are inferred from the location of the request. + requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): + Optional. Specifies what reference routes to calculate as + part of the request in addition to the default route. A + reference route is a route with a different route + calculation objective than the default route. For example an + FUEL_EFFICIENT reference route calculation takes into + account various parameters that would generate an optimal + fuel efficient route. + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + """ + class ReferenceRoute(proto.Enum): + r"""A supported reference route on the ComputeRoutesRequest. + + Values: + REFERENCE_ROUTE_UNSPECIFIED (0): + Not used. Requests containing this value + fail. + FUEL_EFFICIENT (1): + Fuel efficient route. Routes labeled with + this value are determined to be optimized for + parameters such as fuel consumption. + """ + REFERENCE_ROUTE_UNSPECIFIED = 0 + FUEL_EFFICIENT = 1 + + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the route(s). + FUEL_CONSUMPTION (2): + Estimated fuel consumption for the route(s). + TRAFFIC_ON_POLYLINE (3): + Traffic aware polylines for the route(s). + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + FUEL_CONSUMPTION = 2 + TRAFFIC_ON_POLYLINE = 3 + + origin: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + destination: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_waypoint.Waypoint, + ) + intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=gmr_waypoint.Waypoint, + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=4, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=5, + enum=gmr_routing_preference.RoutingPreference, + ) + polyline_quality: polyline.PolylineQuality = proto.Field( + proto.ENUM, + number=6, + enum=polyline.PolylineQuality, + ) + polyline_encoding: polyline.PolylineEncoding = proto.Field( + proto.ENUM, + number=12, + enum=polyline.PolylineEncoding, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + compute_alternative_routes: bool = proto.Field( + proto.BOOL, + number=8, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=9, + message=gmr_route_modifiers.RouteModifiers, + ) + language_code: str = proto.Field( + proto.STRING, + number=10, + ) + units: gmr_units.Units = proto.Field( + proto.ENUM, + number=11, + enum=gmr_units.Units, + ) + requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( + proto.ENUM, + number=14, + enum=ReferenceRoute, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=15, + enum=ExtraComputation, + ) + + +class ComputeRoutesResponse(proto.Message): + r"""ComputeRoutes the response message. + + Attributes: + routes (MutableSequence[google.maps.routing_v2.types.Route]): + Contains an array of computed routes (up to three) when you + specify compute_alternatives_routes, and contains just one + route when you don't. When this array contains multiple + entries, the first one is the most recommended route. If the + array is empty, then it means no route could be found. + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route results with all of the input + preferences, it may fallback to using a + different way of computation. When fallback mode + is used, this field contains detailed info about + the fallback response. Otherwise this field is + unset. + geocoding_results (google.maps.routing_v2.types.GeocodingResults): + Contains geocoding response info for + waypoints specified as addresses. + """ + + routes: MutableSequence[route.Route] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=route.Route, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_fallback_info.FallbackInfo, + ) + geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_geocoding_results.GeocodingResults, + ) + + +class ComputeRouteMatrixRequest(proto.Message): + r"""ComputeRouteMatrix request message + + Attributes: + origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): + Required. Array of origins, which determines the rows of the + response matrix. Several size restrictions apply to the + cardinality of origins and destinations: + + - The number of elements (origins × destinations) must be + no greater than 625 in any case. + - The number of elements (origins × destinations) must be + no greater than 100 if routing_preference is set to + ``TRAFFIC_AWARE_OPTIMAL``. + - The number of waypoints (origins + destinations) + specified as ``place_id`` must be no greater than 50. + destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): + Required. Array of destinations, which + determines the columns of the response matrix. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, an error is returned. You can specify + this option only when the ``travel_mode`` is ``DRIVE`` or + ``TWO_WHEELER``, otherwise the request fails. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't + set this value, this defaults to the time that + you made the request. If you set this value to a + time that has already occurred, the request + fails. + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + """ + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the matrix element(s). + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + + origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteMatrixOrigin', + ) + destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='RouteMatrixDestination', + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=3, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=4, + enum=gmr_routing_preference.RoutingPreference, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=ExtraComputation, + ) + + +class RouteMatrixOrigin(proto.Message): + r"""A single origin for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. Modifiers for every route that + takes this as the origin + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_route_modifiers.RouteModifiers, + ) + + +class RouteMatrixDestination(proto.Message): + r"""A single destination for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + + +class RouteMatrixElement(proto.Message): + r"""Encapsulates route information computed for an + origin/destination pair in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + origin_index (int): + Zero-based index of the origin in the + request. + + This field is a member of `oneof`_ ``_origin_index``. + destination_index (int): + Zero-based index of the destination in the + request. + + This field is a member of `oneof`_ ``_destination_index``. + status (google.rpc.status_pb2.Status): + Error status code for this element. + condition (google.maps.routing_v2.types.RouteMatrixElementCondition): + Indicates whether the route was found or not. + Independent of status. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this + value is the same as ``static_duration``. If you set the + ``routing_preference`` to either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the route + without taking traffic conditions into + consideration. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. For + example: restriction information and toll + information + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route with the given preferences for + this particular origin/destination pair, it may + fall back to using a different mode of + computation. When fallback mode is used, this + field contains detailed information about the + fallback response. Otherwise this field is + unset. + """ + + origin_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + destination_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + condition: 'RouteMatrixElementCondition' = proto.Field( + proto.ENUM, + number=9, + enum='RouteMatrixElementCondition', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=4, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + travel_advisory: route.RouteTravelAdvisory = proto.Field( + proto.MESSAGE, + number=7, + message=route.RouteTravelAdvisory, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=8, + message=gmr_fallback_info.FallbackInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py new file mode 100644 index 000000000000..d7d3a75786b1 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RoutingPreference', + }, +) + + +class RoutingPreference(proto.Enum): + r"""A set of values that specify factors to take into + consideration when calculating the route. + + Values: + ROUTING_PREFERENCE_UNSPECIFIED (0): + No routing preference specified. Default to + ``TRAFFIC_UNAWARE``. + TRAFFIC_UNAWARE (1): + Computes routes without taking live traffic conditions into + consideration. Suitable when traffic conditions don't matter + or are not applicable. Using this value produces the lowest + latency. Note: For ``RouteTravelMode`` DRIVE and TWO_WHEELER + choice of route and duration are based on road network and + average time-independent traffic conditions. Results for a + given request may vary over time due to changes in the road + network, updated average traffic conditions, and the + distributed nature of the service. Results may also vary + between nearly-equivalent routes at any time or frequency. + TRAFFIC_AWARE (2): + Calculates routes taking live traffic conditions into + consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, + some optimizations are applied to significantly reduce + latency. + TRAFFIC_AWARE_OPTIMAL (3): + Calculates the routes taking live traffic + conditions into consideration, without applying + most performance optimizations. Using this value + produces the highest latency. + """ + ROUTING_PREFERENCE_UNSPECIFIED = 0 + TRAFFIC_UNAWARE = 1 + TRAFFIC_AWARE = 2 + TRAFFIC_AWARE_OPTIMAL = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py new file mode 100644 index 000000000000..9a322fff1e94 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'SpeedReadingInterval', + }, +) + + +class SpeedReadingInterval(proto.Message): + r"""Traffic density indicator on a contiguous segment of a polyline or + path. Given a path with points P_0, P_1, ... , P_N (zero-based + index), the SpeedReadingInterval defines an interval and describes + its traffic using the following categories. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_polyline_point_index (int): + The starting index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_start_polyline_point_index``. + end_polyline_point_index (int): + The ending index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_end_polyline_point_index``. + speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): + Traffic speed in this interval. + """ + class Speed(proto.Enum): + r"""The classification of polyline speed based on traffic data. + + Values: + SPEED_UNSPECIFIED (0): + Default value. This value is unused. + NORMAL (1): + Normal speed, no slowdown is detected. + SLOW (2): + Slowdown detected, but no traffic jam formed. + TRAFFIC_JAM (3): + Traffic jam detected. + """ + SPEED_UNSPECIFIED = 0 + NORMAL = 1 + SLOW = 2 + TRAFFIC_JAM = 3 + + start_polyline_point_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + end_polyline_point_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + speed: Speed = proto.Field( + proto.ENUM, + number=3, + enum=Speed, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py new file mode 100644 index 000000000000..3182bd03ac01 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.type import money_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TollInfo', + }, +) + + +class TollInfo(proto.Message): + r"""Encapsulates toll information on a ``Route`` or on a ``RouteLeg``. + + Attributes: + estimated_price (MutableSequence[google.type.money_pb2.Money]): + The monetary amount of tolls for the + corresponding Route or RouteLeg. This list + contains a money amount for each currency that + is expected to be charged by the toll stations. + Typically this list will contain only one item + for routes with tolls in one currency. For + international trips, this list may contain + multiple items to reflect tolls in different + currencies. + """ + + estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=money_pb2.Money, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py new file mode 100644 index 000000000000..05edb1a082c3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py @@ -0,0 +1,348 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TollPass', + }, +) + + +class TollPass(proto.Enum): + r"""List of toll passes around the world that we support. + + Values: + TOLL_PASS_UNSPECIFIED (0): + Not used. If this value is used, then the + request fails. + AU_ETOLL_TAG (82): + Sydney toll pass. See additional details at + https://www.myetoll.com.au. + AU_EWAY_TAG (83): + Sydney toll pass. See additional details at + https://www.tollpay.com.au. + AU_LINKT (2): + Australia-wide toll pass. + See additional details at + https://www.linkt.com.au/. + AR_TELEPASE (3): + Argentina toll pass. See additional details + at https://telepase.com.ar + BR_AUTO_EXPRESO (81): + Brazil toll pass. See additional details at + https://www.autoexpreso.com + BR_CONECTCAR (7): + Brazil toll pass. See additional details at + https://conectcar.com. + BR_MOVE_MAIS (8): + Brazil toll pass. See additional details at + https://movemais.com. + BR_PASSA_RAPIDO (88): + Brazil toll pass. See additional details at + https://pasorapido.gob.do/ + BR_SEM_PARAR (9): + Brazil toll pass. See additional details at + https://www.semparar.com.br. + BR_TAGGY (10): + Brazil toll pass. See additional details at + https://taggy.com.br. + BR_VELOE (11): + Brazil toll pass. See additional details at + https://veloe.com.br/site/onde-usar. + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): + Canada to United States border crossing. + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): + Canada to United States border crossing. + CA_US_BLUE_WATER_EDGE_PASS (18): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_CONNEXION (19): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_NEXUS_CARD (20): + Canada to United States border crossing. + ID_E_TOLL (16): + Indonesia. + E-card provided by multiple banks used to pay + for tolls. All e-cards via banks are charged the + same so only one enum value is needed. E.g. - + Bank Mandiri + https://www.bankmandiri.co.id/e-money - BCA + https://www.bca.co.id/flazz + - BNI + https://www.bni.co.id/id-id/ebanking/tapcash + IN_FASTAG (78): + India. + IN_LOCAL_HP_PLATE_EXEMPT (79): + India, HP state plate exemption. + MX_IAVE (90): + Mexico toll pass. + https://iave.capufe.gob.mx/#/ + MX_PASE (91): + Mexico + https://www.pase.com.mx + MX_QUICKPASS (93): + Mexico + https://operadoravial.com/quick-pass/ + MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): + http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf + MX_TAG_IAVE (12): + Mexico + MX_TAG_TELEVIA (13): + Mexico toll pass company. One of many + operating in Mexico City. See additional details + at https://www.televia.com.mx. + MX_TELEVIA (92): + Mexico toll pass company. One of many + operating in Mexico City. + https://www.televia.com.mx + MX_VIAPASS (14): + Mexico toll pass. See additional details at + https://www.viapass.com.mx/viapass/web_home.aspx. + US_AL_FREEDOM_PASS (21): + AL, USA. + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): + AK, USA. + US_CA_FASTRAK (4): + CA, USA. + US_CA_FASTRAK_CAV_STICKER (86): + Indicates driver has any FasTrak pass in + addition to the DMV issued Clean Air Vehicle + (CAV) sticker. + https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml + US_CO_EXPRESSTOLL (23): + CO, USA. + US_CO_GO_PASS (24): + CO, USA. + US_DE_EZPASSDE (25): + DE, USA. + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): + FL, USA. + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): + FL, USA. + US_FL_EPASS (67): + FL, USA. + US_FL_GIBA_TOLL_PASS (68): + FL, USA. + US_FL_LEEWAY (69): + FL, USA. + US_FL_SUNPASS (70): + FL, USA. + US_FL_SUNPASS_PRO (71): + FL, USA. + US_IL_EZPASSIL (73): + IL, USA. + US_IL_IPASS (72): + IL, USA. + US_IN_EZPASSIN (26): + IN, USA. + US_KS_BESTPASS_HORIZON (27): + KS, USA. + US_KS_KTAG (28): + KS, USA. + US_KS_NATIONALPASS (29): + KS, USA. + US_KS_PREPASS_ELITEPASS (30): + KS, USA. + US_KY_RIVERLINK (31): + KY, USA. + US_LA_GEAUXPASS (32): + LA, USA. + US_LA_TOLL_TAG (33): + LA, USA. + US_MA_EZPASSMA (6): + MA, USA. + US_MD_EZPASSMD (34): + MD, USA. + US_ME_EZPASSME (35): + ME, USA. + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): + MI, USA. + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): + MI, USA. + US_MI_IQ_PROX_CARD (38): + MI, USA. + US_MI_MACKINAC_BRIDGE_MAC_PASS (39): + MI, USA. + US_MI_NEXPRESS_TOLL (40): + MI, USA. + US_MN_EZPASSMN (41): + MN, USA. + US_NC_EZPASSNC (42): + NC, USA. + US_NC_PEACH_PASS (87): + NC, USA. + US_NC_QUICK_PASS (43): + NC, USA. + US_NH_EZPASSNH (80): + NH, USA. + US_NJ_DOWNBEACH_EXPRESS_PASS (75): + NJ, USA. + US_NJ_EZPASSNJ (74): + NJ, USA. + US_NY_EXPRESSPASS (76): + NY, USA. + US_NY_EZPASSNY (77): + NY, USA. + US_OH_EZPASSOH (44): + OH, USA. + US_PA_EZPASSPA (45): + PA, USA. + US_RI_EZPASSRI (46): + RI, USA. + US_SC_PALPASS (47): + SC, USA. + US_TX_BANCPASS (48): + TX, USA. + US_TX_DEL_RIO_PASS (49): + TX, USA. + US_TX_EFAST_PASS (50): + TX, USA. + US_TX_EAGLE_PASS_EXPRESS_CARD (51): + TX, USA. + US_TX_EPTOLL (52): + TX, USA. + US_TX_EZ_CROSS (53): + TX, USA. + US_TX_EZTAG (54): + TX, USA. + US_TX_LAREDO_TRADE_TAG (55): + TX, USA. + US_TX_PLUSPASS (56): + TX, USA. + US_TX_TOLLTAG (57): + TX, USA. + US_TX_TXTAG (58): + TX, USA. + US_TX_XPRESS_CARD (59): + TX, USA. + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): + UT, USA. + US_VA_EZPASSVA (61): + VA, USA. + US_WA_BREEZEBY (17): + WA, USA. + US_WA_GOOD_TO_GO (1): + WA, USA. + US_WV_EZPASSWV (62): + WV, USA. + US_WV_MEMORIAL_BRIDGE_TICKETS (63): + WV, USA. + US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): + WV, USA. + """ + TOLL_PASS_UNSPECIFIED = 0 + AU_ETOLL_TAG = 82 + AU_EWAY_TAG = 83 + AU_LINKT = 2 + AR_TELEPASE = 3 + BR_AUTO_EXPRESO = 81 + BR_CONECTCAR = 7 + BR_MOVE_MAIS = 8 + BR_PASSA_RAPIDO = 88 + BR_SEM_PARAR = 9 + BR_TAGGY = 10 + BR_VELOE = 11 + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 + CA_US_BLUE_WATER_EDGE_PASS = 18 + CA_US_CONNEXION = 19 + CA_US_NEXUS_CARD = 20 + ID_E_TOLL = 16 + IN_FASTAG = 78 + IN_LOCAL_HP_PLATE_EXEMPT = 79 + MX_IAVE = 90 + MX_PASE = 91 + MX_QUICKPASS = 93 + MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 + MX_TAG_IAVE = 12 + MX_TAG_TELEVIA = 13 + MX_TELEVIA = 92 + MX_VIAPASS = 14 + US_AL_FREEDOM_PASS = 21 + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 + US_CA_FASTRAK = 4 + US_CA_FASTRAK_CAV_STICKER = 86 + US_CO_EXPRESSTOLL = 23 + US_CO_GO_PASS = 24 + US_DE_EZPASSDE = 25 + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 + US_FL_EPASS = 67 + US_FL_GIBA_TOLL_PASS = 68 + US_FL_LEEWAY = 69 + US_FL_SUNPASS = 70 + US_FL_SUNPASS_PRO = 71 + US_IL_EZPASSIL = 73 + US_IL_IPASS = 72 + US_IN_EZPASSIN = 26 + US_KS_BESTPASS_HORIZON = 27 + US_KS_KTAG = 28 + US_KS_NATIONALPASS = 29 + US_KS_PREPASS_ELITEPASS = 30 + US_KY_RIVERLINK = 31 + US_LA_GEAUXPASS = 32 + US_LA_TOLL_TAG = 33 + US_MA_EZPASSMA = 6 + US_MD_EZPASSMD = 34 + US_ME_EZPASSME = 35 + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 + US_MI_IQ_PROX_CARD = 38 + US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 + US_MI_NEXPRESS_TOLL = 40 + US_MN_EZPASSMN = 41 + US_NC_EZPASSNC = 42 + US_NC_PEACH_PASS = 87 + US_NC_QUICK_PASS = 43 + US_NH_EZPASSNH = 80 + US_NJ_DOWNBEACH_EXPRESS_PASS = 75 + US_NJ_EZPASSNJ = 74 + US_NY_EXPRESSPASS = 76 + US_NY_EZPASSNY = 77 + US_OH_EZPASSOH = 44 + US_PA_EZPASSPA = 45 + US_RI_EZPASSRI = 46 + US_SC_PALPASS = 47 + US_TX_BANCPASS = 48 + US_TX_DEL_RIO_PASS = 49 + US_TX_EFAST_PASS = 50 + US_TX_EAGLE_PASS_EXPRESS_CARD = 51 + US_TX_EPTOLL = 52 + US_TX_EZ_CROSS = 53 + US_TX_EZTAG = 54 + US_TX_LAREDO_TRADE_TAG = 55 + US_TX_PLUSPASS = 56 + US_TX_TOLLTAG = 57 + US_TX_TXTAG = 58 + US_TX_XPRESS_CARD = 59 + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 + US_VA_EZPASSVA = 61 + US_WA_BREEZEBY = 17 + US_WA_GOOD_TO_GO = 1 + US_WV_EZPASSWV = 62 + US_WV_MEMORIAL_BRIDGE_TICKETS = 63 + US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py new file mode 100644 index 000000000000..93cfaf1ee04c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Units', + }, +) + + +class Units(proto.Enum): + r"""A set of values that specify the unit of measure used in the + display. + + Values: + UNITS_UNSPECIFIED (0): + Units of measure not specified. Defaults to + the unit of measure inferred from the request. + METRIC (1): + Metric units of measure. + IMPERIAL (2): + Imperial (English) units of measure. + """ + UNITS_UNSPECIFIED = 0 + METRIC = 1 + IMPERIAL = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py new file mode 100644 index 000000000000..a94a99025c80 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'VehicleEmissionType', + }, +) + + +class VehicleEmissionType(proto.Enum): + r"""A set of values describing the vehicle's emission type. + Applies only to the DRIVE travel mode. + + Values: + VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): + No emission type specified. Default to + GASOLINE. + GASOLINE (1): + Gasoline/petrol fueled vehicle. + ELECTRIC (2): + Electricity powered vehicle. + HYBRID (3): + Hybrid fuel (such as gasoline + electric) + vehicle. + DIESEL (4): + Diesel fueled vehicle. + """ + VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 + GASOLINE = 1 + ELECTRIC = 2 + HYBRID = 3 + DIESEL = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py new file mode 100644 index 000000000000..2d71bb0a70a0 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import vehicle_emission_type + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'VehicleInfo', + }, +) + + +class VehicleInfo(proto.Message): + r"""Encapsulates the vehicle information, such as the license + plate last character. + + Attributes: + emission_type (google.maps.routing_v2.types.VehicleEmissionType): + Describes the vehicle's emission type. + Applies only to the DRIVE travel mode. + """ + + emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( + proto.ENUM, + number=2, + enum=vehicle_emission_type.VehicleEmissionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py new file mode 100644 index 000000000000..c25013cfd086 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import location as gmr_location + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Waypoint', + }, +) + + +class Waypoint(proto.Message): + r"""Encapsulates a waypoint. Waypoints mark both the beginning + and end of a route, and include intermediate stops along the + route. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location (google.maps.routing_v2.types.Location): + A point specified using geographic + coordinates, including an optional heading. + + This field is a member of `oneof`_ ``location_type``. + place_id (str): + The POI Place ID associated with the + waypoint. + + This field is a member of `oneof`_ ``location_type``. + address (str): + Human readable address or a plus code. + See https://plus.codes for details. + + This field is a member of `oneof`_ ``location_type``. + via (bool): + Marks this waypoint as a milestone rather a stopping point. + For each non-via waypoint in the request, the response + appends an entry to the ``legs`` array to provide the + details for stopovers on that leg of the trip. Set this + value to true when you want the route to pass through this + waypoint without stopping over. Via waypoints don't cause an + entry to be added to the ``legs`` array, but they do route + the journey through the waypoint. You can only set this + value on waypoints that are intermediates. The request fails + if you set this field on terminal waypoints. If + ``ComputeRoutesRequest.optimize_waypoint_order`` is set to + true then this field cannot be set to true; otherwise, the + request fails. + vehicle_stopover (bool): + Indicates that the waypoint is meant for vehicles to stop + at, where the intention is to either pickup or drop-off. + When you set this value, the calculated route won't include + non-\ ``via`` waypoints on roads that are unsuitable for + pickup and drop-off. This option works only for ``DRIVE`` + and ``TWO_WHEELER`` travel modes, and when the + ``location_type`` is ``location``. + side_of_road (bool): + Indicates that the location of this waypoint is meant to + have a preference for the vehicle to stop at a particular + side of road. When you set this value, the route will pass + through the location so that the vehicle can stop at the + side of road that the location is biased towards from the + center of the road. This option works only for 'DRIVE' and + 'TWO_WHEELER' travel modes. + """ + + location: gmr_location.Location = proto.Field( + proto.MESSAGE, + number=1, + oneof='location_type', + message=gmr_location.Location, + ) + place_id: str = proto.Field( + proto.STRING, + number=2, + oneof='location_type', + ) + address: str = proto.Field( + proto.STRING, + number=7, + oneof='location_type', + ) + via: bool = proto.Field( + proto.BOOL, + number=3, + ) + vehicle_stopover: bool = proto.Field( + proto.BOOL, + number=4, + ) + side_of_road: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py new file mode 100644 index 000000000000..59757e684c85 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/routing_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py new file mode 100644 index 000000000000..381f53f7a26e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py new file mode 100644 index 000000000000..125691404b0b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py new file mode 100644 index 000000000000..c978c3e55cd7 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py new file mode 100644 index 000000000000..ca13730e4ddc --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json new file mode 100644 index 000000000000..b5ed5aca319c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json @@ -0,0 +1,321 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.routing.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-maps-routing", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_route_matrix_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_route_matrix_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_routes_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py new file mode 100644 index 000000000000..291c4ea93db5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class routingCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'extra_computations', ), + 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'units', 'requested_reference_routes', 'extra_computations', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=routingCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the routing client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py new file mode 100644 index 000000000000..b93d9d947fd8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-maps-routing' + + +description = "Google Maps Routing API client library" + +version = {} +with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "google-geo-type >= 0.1.0, <1.0.0dev", +] +url = "https://github.com/googleapis/python-maps-routing" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.maps"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt new file mode 100644 index 000000000000..33ac865954a6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 +google-geo-type==0.1.0 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py new file mode 100644 index 000000000000..55f7b3a4ba31 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py @@ -0,0 +1,1750 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.maps.routing_v2.services.routes import RoutesAsyncClient +from google.maps.routing_v2.services.routes import RoutesClient +from google.maps.routing_v2.services.routes import transports +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routes_service +from google.maps.routing_v2.types import routing_preference +from google.maps.routing_v2.types import toll_passes +from google.maps.routing_v2.types import units +from google.maps.routing_v2.types import vehicle_emission_type +from google.maps.routing_v2.types import vehicle_info +from google.maps.routing_v2.types import waypoint +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +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 RoutesClient._get_default_mtls_endpoint(None) is None + assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RoutesGrpcTransport, "grpc"), + (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RoutesRestTransport, "rest"), +]) +def test_routes_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +def test_routes_client_get_transport_class(): + transport = RoutesClient.get_transport_class() + available_transports = [ + transports.RoutesGrpcTransport, + transports.RoutesRestTransport, + ] + assert transport in available_transports + + transport = RoutesClient.get_transport_class("grpc") + assert transport == transports.RoutesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +def test_routes_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RoutesClient, transports.RoutesRestTransport, "rest", "true"), + (RoutesClient, transports.RoutesRestTransport, "rest", "false"), +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_routes_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + RoutesClient, RoutesAsyncClient +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +def test_routes_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +def test_routes_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RoutesClient, transports.RoutesRestTransport, "rest", None), +]) +def test_routes_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_routes_client_client_options_from_dict(): + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RoutesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_routes_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "routes.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes(request_type, transport: str = 'grpc'): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = routes_service.ComputeRoutesResponse( + ) + response = client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + client.compute_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + +@pytest.mark.asyncio +async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( + )) + response = await client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +@pytest.mark.asyncio +async def test_compute_routes_async_from_dict(): + await test_compute_routes_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix(request_type, transport: str = 'grpc'): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([routes_service.RouteMatrixElement()]) + response = client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, routes_service.RouteMatrixElement) + + +def test_compute_route_matrix_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + client.compute_route_matrix() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + +@pytest.mark.asyncio +async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) + response = await client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, routes_service.RouteMatrixElement) + + +@pytest.mark.asyncio +async def test_compute_route_matrix_async_from_dict(): + await test_compute_route_matrix_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes_rest(request_type): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = routes_service.ComputeRoutesResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.compute_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): + transport_class = transports.RoutesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.ComputeRoutesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.compute_routes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_routes_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_routes._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_routes_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) + + request = routes_service.ComputeRoutesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.ComputeRoutesResponse() + + client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_routes_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRoutesRequest): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.compute_routes(request) + + +def test_compute_routes_rest_error(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix_rest(request_type): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = routes_service.RouteMatrixElement( + origin_index=1279, + destination_index=1817, + condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, + distance_meters=1594, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.compute_route_matrix(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.RouteMatrixElement) + assert response.origin_index == 1279 + assert response.destination_index == 1817 + assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS + assert response.distance_meters == 1594 + + +def test_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): + transport_class = transports.RoutesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.RouteMatrixElement() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.compute_route_matrix(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_route_matrix_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_route_matrix_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) + req.return_value._content = "[{}]".format(req.return_value._content) + + request = routes_service.ComputeRouteMatrixRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.RouteMatrixElement() + + client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_route_matrix_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.compute_route_matrix(request) + + +def test_compute_route_matrix_rest_error(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutesClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RoutesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RoutesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = RoutesClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RoutesGrpcTransport, + ) + +def test_routes_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_routes_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'compute_routes', + 'compute_route_matrix', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_routes_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +def test_routes_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport() + adc.assert_called_once() + + +def test_routes_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RoutesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + ], +) +def test_routes_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, + ], +) +def test_routes_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RoutesGrpcTransport, grpc_helpers), + (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_routes_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "routes.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_routes_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.RoutesRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_routes_host_no_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_routes_host_with_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_routes_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RoutesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RoutesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.compute_routes._session + session2 = client2.transport.compute_routes._session + assert session1 != session2 + session1 = client1.transport.compute_route_matrix._session + session2 = client2.transport.compute_route_matrix._session + assert session1 != session2 +def test_routes_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_routes_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + 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 + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + 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=cred, + credentials_file=None, + scopes=None, + 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 + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_transport_channel_mtls_with_adc( + transport_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), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + 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 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RoutesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RoutesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = RoutesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RoutesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RoutesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RoutesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = RoutesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RoutesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RoutesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RoutesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: + transport_class = RoutesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (RoutesClient, transports.RoutesGrpcTransport), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From b236357c80938ce3f1231e94c658c2cc998e9ef7 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 17 Mar 2023 18:36:53 +0000 Subject: [PATCH 06/12] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../google-maps-routing/v2/.coveragerc | 13 - .../google-maps-routing/v2/.flake8 | 33 - .../google-maps-routing/v2/MANIFEST.in | 2 - .../google-maps-routing/v2/README.rst | 49 - .../google-maps-routing/v2/docs/conf.py | 376 ---- .../google-maps-routing/v2/docs/index.rst | 7 - .../v2/docs/routing_v2/routes.rst | 6 - .../v2/docs/routing_v2/services.rst | 6 - .../v2/docs/routing_v2/types.rst | 6 - .../v2/google/maps/routing/__init__.py | 97 - .../v2/google/maps/routing/gapic_version.py | 16 - .../v2/google/maps/routing/py.typed | 2 - .../v2/google/maps/routing_v2/__init__.py | 98 - .../maps/routing_v2/gapic_metadata.json | 58 - .../google/maps/routing_v2/gapic_version.py | 16 - .../v2/google/maps/routing_v2/py.typed | 2 - .../maps/routing_v2/services/__init__.py | 15 - .../routing_v2/services/routes/__init__.py | 22 - .../services/routes/async_client.py | 416 ---- .../maps/routing_v2/services/routes/client.py | 613 ------ .../services/routes/transports/__init__.py | 38 - .../services/routes/transports/base.py | 161 -- .../services/routes/transports/grpc.py | 363 ---- .../routes/transports/grpc_asyncio.py | 362 ---- .../services/routes/transports/rest.py | 417 ---- .../google/maps/routing_v2/types/__init__.py | 105 - .../maps/routing_v2/types/fallback_info.py | 103 - .../routing_v2/types/geocoding_results.py | 125 -- .../google/maps/routing_v2/types/location.py | 62 - .../google/maps/routing_v2/types/maneuver.py | 96 - .../types/navigation_instruction.py | 58 - .../google/maps/routing_v2/types/polyline.py | 113 -- .../v2/google/maps/routing_v2/types/route.py | 409 ---- .../maps/routing_v2/types/route_label.py | 57 - .../maps/routing_v2/types/route_modifiers.py | 97 - .../routing_v2/types/route_travel_mode.py | 59 - .../maps/routing_v2/types/routes_service.py | 512 ----- .../routing_v2/types/routing_preference.py | 67 - .../types/speed_reading_interval.py | 89 - .../google/maps/routing_v2/types/toll_info.py | 56 - .../maps/routing_v2/types/toll_passes.py | 348 ---- .../v2/google/maps/routing_v2/types/units.py | 49 - .../routing_v2/types/vehicle_emission_type.py | 56 - .../maps/routing_v2/types/vehicle_info.py | 50 - .../google/maps/routing_v2/types/waypoint.py | 123 -- .../google-maps-routing/v2/mypy.ini | 3 - .../google-maps-routing/v2/noxfile.py | 184 -- ...rated_routes_compute_route_matrix_async.py | 52 - ...erated_routes_compute_route_matrix_sync.py | 52 - ...2_generated_routes_compute_routes_async.py | 51 - ...v2_generated_routes_compute_routes_sync.py | 51 - ...ippet_metadata_google.maps.routing.v2.json | 321 --- .../v2/scripts/fixup_routing_v2_keywords.py | 177 -- .../google-maps-routing/v2/setup.py | 91 - .../v2/testing/constraints-3.10.txt | 7 - .../v2/testing/constraints-3.11.txt | 7 - .../v2/testing/constraints-3.12.txt | 7 - .../v2/testing/constraints-3.7.txt | 10 - .../v2/testing/constraints-3.8.txt | 7 - .../v2/testing/constraints-3.9.txt | 7 - .../google-maps-routing/v2/tests/__init__.py | 16 - .../v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/routing_v2/__init__.py | 16 - .../unit/gapic/routing_v2/test_routes.py | 1750 ----------------- packages/google-maps-routing/setup.py | 1 + .../testing/constraints-3.10.txt | 1 + .../testing/constraints-3.11.txt | 1 + .../testing/constraints-3.12.txt | 1 + .../testing/constraints-3.7.txt | 1 + .../testing/constraints-3.8.txt | 1 + .../testing/constraints-3.9.txt | 1 + 72 files changed, 7 insertions(+), 8669 deletions(-) delete mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc delete mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 delete mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini delete mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py diff --git a/owl-bot-staging/google-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc deleted file mode 100644 index d0ce5597b0a9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/routing/__init__.py - google/maps/routing/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.flake8 +++ /dev/null @@ -1,33 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in deleted file mode 100644 index c5b56c111c00..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/routing *.py -recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst deleted file mode 100644 index f0002366e552..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Routing API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Maps Routing API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py deleted file mode 100644 index d7a10abed96b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-maps-routing documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -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"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-maps-routing" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# 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"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# 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 - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -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 = { - "description": "Google Maps Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# 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 - -# 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 - -# 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, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# 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 = [] - -# 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' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is 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 = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# 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' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# 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' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-maps-routing-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- 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', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-maps-routing.tex", - u"google-maps-routing 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 - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# 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 = [ - ( - root_doc, - "google-maps-routing", - u"Google Maps Routing Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-maps-routing", - u"google-maps-routing Documentation", - author, - "google-maps-routing", - "GAPIC library for Google Maps Routing API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# 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), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst deleted file mode 100644 index e2563dd88ee9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - routing_v2/services - routing_v2/types diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst deleted file mode 100644 index 3d52309cddae..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst +++ /dev/null @@ -1,6 +0,0 @@ -Routes ------------------------- - -.. automodule:: google.maps.routing_v2.services.routes - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst deleted file mode 100644 index e96568dc434c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Routing v2 API -======================================= -.. toctree:: - :maxdepth: 2 - - routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst deleted file mode 100644 index 176a5a812cf8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Routing v2 API -==================================== - -.. automodule:: google.maps.routing_v2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py deleted file mode 100644 index 59020a3484c3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.maps.routing import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.routing_v2.services.routes.client import RoutesClient -from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient - -from google.maps.routing_v2.types.fallback_info import FallbackInfo -from google.maps.routing_v2.types.fallback_info import FallbackReason -from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode -from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint -from google.maps.routing_v2.types.geocoding_results import GeocodingResults -from google.maps.routing_v2.types.location import Location -from google.maps.routing_v2.types.maneuver import Maneuver -from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction -from google.maps.routing_v2.types.polyline import Polyline -from google.maps.routing_v2.types.polyline import PolylineEncoding -from google.maps.routing_v2.types.polyline import PolylineQuality -from google.maps.routing_v2.types.route import Route -from google.maps.routing_v2.types.route import RouteLeg -from google.maps.routing_v2.types.route import RouteLegStep -from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory -from google.maps.routing_v2.types.route import RouteLegTravelAdvisory -from google.maps.routing_v2.types.route import RouteTravelAdvisory -from google.maps.routing_v2.types.route_label import RouteLabel -from google.maps.routing_v2.types.route_modifiers import RouteModifiers -from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode -from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse -from google.maps.routing_v2.types.routes_service import RouteMatrixDestination -from google.maps.routing_v2.types.routes_service import RouteMatrixElement -from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin -from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition -from google.maps.routing_v2.types.routing_preference import RoutingPreference -from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval -from google.maps.routing_v2.types.toll_info import TollInfo -from google.maps.routing_v2.types.toll_passes import TollPass -from google.maps.routing_v2.types.units import Units -from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType -from google.maps.routing_v2.types.vehicle_info import VehicleInfo -from google.maps.routing_v2.types.waypoint import Waypoint - -__all__ = ('RoutesClient', - 'RoutesAsyncClient', - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py deleted file mode 100644 index 405b1cebcf15..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py deleted file mode 100644 index cd9d694f63c6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.maps.routing_v2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.routes import RoutesClient -from .services.routes import RoutesAsyncClient - -from .types.fallback_info import FallbackInfo -from .types.fallback_info import FallbackReason -from .types.fallback_info import FallbackRoutingMode -from .types.geocoding_results import GeocodedWaypoint -from .types.geocoding_results import GeocodingResults -from .types.location import Location -from .types.maneuver import Maneuver -from .types.navigation_instruction import NavigationInstruction -from .types.polyline import Polyline -from .types.polyline import PolylineEncoding -from .types.polyline import PolylineQuality -from .types.route import Route -from .types.route import RouteLeg -from .types.route import RouteLegStep -from .types.route import RouteLegStepTravelAdvisory -from .types.route import RouteLegTravelAdvisory -from .types.route import RouteTravelAdvisory -from .types.route_label import RouteLabel -from .types.route_modifiers import RouteModifiers -from .types.route_travel_mode import RouteTravelMode -from .types.routes_service import ComputeRouteMatrixRequest -from .types.routes_service import ComputeRoutesRequest -from .types.routes_service import ComputeRoutesResponse -from .types.routes_service import RouteMatrixDestination -from .types.routes_service import RouteMatrixElement -from .types.routes_service import RouteMatrixOrigin -from .types.routes_service import RouteMatrixElementCondition -from .types.routing_preference import RoutingPreference -from .types.speed_reading_interval import SpeedReadingInterval -from .types.toll_info import TollInfo -from .types.toll_passes import TollPass -from .types.units import Units -from .types.vehicle_emission_type import VehicleEmissionType -from .types.vehicle_info import VehicleInfo -from .types.waypoint import Waypoint - -__all__ = ( - 'RoutesAsyncClient', -'ComputeRouteMatrixRequest', -'ComputeRoutesRequest', -'ComputeRoutesResponse', -'FallbackInfo', -'FallbackReason', -'FallbackRoutingMode', -'GeocodedWaypoint', -'GeocodingResults', -'Location', -'Maneuver', -'NavigationInstruction', -'Polyline', -'PolylineEncoding', -'PolylineQuality', -'Route', -'RouteLabel', -'RouteLeg', -'RouteLegStep', -'RouteLegStepTravelAdvisory', -'RouteLegTravelAdvisory', -'RouteMatrixDestination', -'RouteMatrixElement', -'RouteMatrixElementCondition', -'RouteMatrixOrigin', -'RouteModifiers', -'RouteTravelAdvisory', -'RouteTravelMode', -'RoutesClient', -'RoutingPreference', -'SpeedReadingInterval', -'TollInfo', -'TollPass', -'Units', -'VehicleEmissionType', -'VehicleInfo', -'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json deleted file mode 100644 index 8382cea1d39a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json +++ /dev/null @@ -1,58 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.routing_v2", - "protoPackage": "google.maps.routing.v2", - "schema": "1.0", - "services": { - "Routes": { - "clients": { - "grpc": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RoutesAsyncClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "rest": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py deleted file mode 100644 index 405b1cebcf15..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py deleted file mode 100644 index e8e1c3845db5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py deleted file mode 100644 index ff3f8f71863f..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import RoutesClient -from .async_client import RoutesAsyncClient - -__all__ = ( - 'RoutesClient', - 'RoutesAsyncClient', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py deleted file mode 100644 index 7f8df74a140b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union - -from google.maps.routing_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .client import RoutesClient - - -class RoutesAsyncClient: - """The Routes API.""" - - _client: RoutesClient - - DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RoutesClient.common_folder_path) - parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) - common_organization_path = staticmethod(RoutesClient.common_organization_path) - parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) - common_project_path = staticmethod(RoutesClient.common_project_path) - parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) - common_location_path = staticmethod(RoutesClient.common_location_path) - parse_common_location_path = staticmethod(RoutesClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(RoutesClient).get_transport_class, type(RoutesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, RoutesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.RoutesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RoutesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # Create or coerce a protobuf request object. - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.compute_routes, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - # Create or coerce a protobuf request object. - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.compute_route_matrix, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RoutesAsyncClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py deleted file mode 100644 index 1943383c7246..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py +++ /dev/null @@ -1,613 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast - -from google.maps.routing_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RoutesGrpcTransport -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .transports.rest import RoutesRestTransport - - -class RoutesClientMeta(type): - """Metaclass for the Routes client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] - _transport_registry["grpc"] = RoutesGrpcTransport - _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport - _transport_registry["rest"] = RoutesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RoutesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class RoutesClient(metaclass=RoutesClientMeta): - """The Routes API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "routes.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RoutesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, RoutesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, RoutesTransport): - # transport is a RoutesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a routes_service.ComputeRoutesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, routes_service.ComputeRoutesRequest): - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_routes] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[routes_service.RouteMatrixElement]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - Iterable[google.maps.routing_v2.types.RouteMatrixElement]: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a routes_service.ComputeRouteMatrixRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, routes_service.ComputeRouteMatrixRequest): - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "RoutesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RoutesClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py deleted file mode 100644 index a15967f001c9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import RoutesTransport -from .grpc import RoutesGrpcTransport -from .grpc_asyncio import RoutesGrpcAsyncIOTransport -from .rest import RoutesRestTransport -from .rest import RoutesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] -_transport_registry['grpc'] = RoutesGrpcTransport -_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport -_transport_registry['rest'] = RoutesRestTransport - -__all__ = ( - 'RoutesTransport', - 'RoutesGrpcTransport', - 'RoutesGrpcAsyncIOTransport', - 'RoutesRestTransport', - 'RoutesRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py deleted file mode 100644 index a6fa68993eca..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py +++ /dev/null @@ -1,161 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.maps.routing_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.maps.routing_v2.types import routes_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class RoutesTransport(abc.ABC): - """Abstract transport class for Routes.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'routes.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.compute_routes: gapic_v1.method.wrap_method( - self.compute_routes, - default_timeout=None, - client_info=client_info, - ), - self.compute_route_matrix: gapic_v1.method.wrap_method( - self.compute_route_matrix, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Union[ - routes_service.ComputeRoutesResponse, - Awaitable[routes_service.ComputeRoutesResponse] - ]]: - raise NotImplementedError() - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Union[ - routes_service.RouteMatrixElement, - Awaitable[routes_service.RouteMatrixElement] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RoutesTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py deleted file mode 100644 index 8316c8b03587..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py +++ /dev/null @@ -1,363 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO - - -class RoutesGrpcTransport(RoutesTransport): - """gRPC backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - ~.ComputeRoutesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self.grpc_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - ~.RouteMatrixElement]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RoutesGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py deleted file mode 100644 index 752c5eaefc33..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py +++ /dev/null @@ -1,362 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO -from .grpc import RoutesGrpcTransport - - -class RoutesGrpcAsyncIOTransport(RoutesTransport): - """gRPC AsyncIO backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Awaitable[routes_service.ComputeRoutesResponse]]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - Awaitable[~.ComputeRoutesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self.grpc_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Awaitable[routes_service.RouteMatrixElement]]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - Awaitable[~.RouteMatrixElement]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'RoutesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py deleted file mode 100644 index c7fdf524b0c7..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.maps.routing_v2.types import routes_service - -from .base import RoutesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class RoutesRestInterceptor: - """Interceptor for Routes. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the RoutesRestTransport. - - .. code-block:: python - class MyCustomRoutesInterceptor(RoutesRestInterceptor): - def pre_compute_route_matrix(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_route_matrix(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_compute_routes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_routes(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) - client = RoutesClient(transport=transport) - - - """ - def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: - """Post-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compute_routes - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: - """Post-rpc interceptor for compute_routes - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class RoutesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RoutesRestInterceptor - - -class RoutesRestTransport(RoutesTransport): - """REST backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[RoutesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or RoutesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ComputeRouteMatrix(RoutesRestStub): - def __hash__(self): - return hash("ComputeRouteMatrix") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: routes_service.ComputeRouteMatrixRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> rest_streaming.ResponseIterator: - r"""Call the compute route matrix method over HTTP. - - Args: - request (~.routes_service.ComputeRouteMatrixRequest): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.routes_service.RouteMatrixElement: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/distanceMatrix/v2:computeRouteMatrix', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) - pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) - resp = self._interceptor.post_compute_route_matrix(resp) - return resp - - class _ComputeRoutes(RoutesRestStub): - def __hash__(self): - return hash("ComputeRoutes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: routes_service.ComputeRoutesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> routes_service.ComputeRoutesResponse: - r"""Call the compute routes method over HTTP. - - Args: - request (~.routes_service.ComputeRoutesRequest): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.routes_service.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/directions/v2:computeRoutes', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_compute_routes(request, metadata) - pb_request = routes_service.ComputeRoutesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = routes_service.ComputeRoutesResponse() - pb_resp = routes_service.ComputeRoutesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_compute_routes(resp) - return resp - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RoutesRestTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py deleted file mode 100644 index 7323899cfc30..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .fallback_info import ( - FallbackInfo, - FallbackReason, - FallbackRoutingMode, -) -from .geocoding_results import ( - GeocodedWaypoint, - GeocodingResults, -) -from .location import ( - Location, -) -from .navigation_instruction import ( - NavigationInstruction, -) -from .polyline import ( - Polyline, - PolylineEncoding, - PolylineQuality, -) -from .route import ( - Route, - RouteLeg, - RouteLegStep, - RouteLegStepTravelAdvisory, - RouteLegTravelAdvisory, - RouteTravelAdvisory, -) -from .route_modifiers import ( - RouteModifiers, -) -from .routes_service import ( - ComputeRouteMatrixRequest, - ComputeRoutesRequest, - ComputeRoutesResponse, - RouteMatrixDestination, - RouteMatrixElement, - RouteMatrixOrigin, - RouteMatrixElementCondition, -) -from .speed_reading_interval import ( - SpeedReadingInterval, -) -from .toll_info import ( - TollInfo, -) -from .vehicle_info import ( - VehicleInfo, -) -from .waypoint import ( - Waypoint, -) - -__all__ = ( - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py deleted file mode 100644 index 99670aafac25..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'FallbackReason', - 'FallbackRoutingMode', - 'FallbackInfo', - }, -) - - -class FallbackReason(proto.Enum): - r"""Reasons for using fallback response. - - Values: - FALLBACK_REASON_UNSPECIFIED (0): - No fallback reason specified. - SERVER_ERROR (1): - A server error happened while calculating - routes with your preferred routing mode, but we - were able to return a result calculated by an - alternative mode. - LATENCY_EXCEEDED (2): - We were not able to finish the calculation - with your preferred routing mode on time, but we - were able to return a result calculated by an - alternative mode. - """ - FALLBACK_REASON_UNSPECIFIED = 0 - SERVER_ERROR = 1 - LATENCY_EXCEEDED = 2 - - -class FallbackRoutingMode(proto.Enum): - r"""Actual routing mode used for returned fallback response. - - Values: - FALLBACK_ROUTING_MODE_UNSPECIFIED (0): - Not used. - FALLBACK_TRAFFIC_UNAWARE (1): - Indicates the "TRAFFIC_UNAWARE" routing mode was used to - compute the response. - FALLBACK_TRAFFIC_AWARE (2): - Indicates the "TRAFFIC_AWARE" routing mode was used to - compute the response. - """ - FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 - FALLBACK_TRAFFIC_UNAWARE = 1 - FALLBACK_TRAFFIC_AWARE = 2 - - -class FallbackInfo(proto.Message): - r"""Information related to how and why a fallback result was - used. If this field is set, then it means the server used a - different routing mode from your preferred mode as fallback. - - Attributes: - routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): - Routing mode used for the response. If - fallback was triggered, the mode may be - different from routing preference set in the - original client request. - reason (google.maps.routing_v2.types.FallbackReason): - The reason why fallback response was used - instead of the original response. This field is - only populated when the fallback mode is - triggered and the fallback response is returned. - """ - - routing_mode: 'FallbackRoutingMode' = proto.Field( - proto.ENUM, - number=1, - enum='FallbackRoutingMode', - ) - reason: 'FallbackReason' = proto.Field( - proto.ENUM, - number=2, - enum='FallbackReason', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py deleted file mode 100644 index ffa385a59a75..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py +++ /dev/null @@ -1,125 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'GeocodingResults', - 'GeocodedWaypoint', - }, -) - - -class GeocodingResults(proto.Message): - r"""Contains GeocodedWaypoints for origin, destination and - intermediate waypoints. Only populated for address waypoints. - - Attributes: - origin (google.maps.routing_v2.types.GeocodedWaypoint): - Origin geocoded waypoint. - destination (google.maps.routing_v2.types.GeocodedWaypoint): - Destination geocoded waypoint. - intermediates (MutableSequence[google.maps.routing_v2.types.GeocodedWaypoint]): - A list of intermediate geocoded waypoints - each containing an index field that corresponds - to the zero-based position of the waypoint in - the order they were specified in the request. - """ - - origin: 'GeocodedWaypoint' = proto.Field( - proto.MESSAGE, - number=1, - message='GeocodedWaypoint', - ) - destination: 'GeocodedWaypoint' = proto.Field( - proto.MESSAGE, - number=2, - message='GeocodedWaypoint', - ) - intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='GeocodedWaypoint', - ) - - -class GeocodedWaypoint(proto.Message): - r"""Details about the locations used as waypoints. Only populated - for address waypoints. Includes details about the geocoding - results for the purposes of determining what the address was - geocoded to. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - geocoder_status (google.rpc.status_pb2.Status): - Indicates the status code resulting from the - geocoding operation. - intermediate_waypoint_request_index (int): - The index of the corresponding intermediate - waypoint in the request. Only populated if the - corresponding waypoint is an intermediate - waypoint. - - This field is a member of `oneof`_ ``_intermediate_waypoint_request_index``. - type_ (MutableSequence[str]): - The type(s) of the result, in the form of - zero or more type tags. Supported types: - https://developers.google.com/maps/documentation/geocoding/requests-geocoding#Types - partial_match (bool): - Indicates that the geocoder did not return an - exact match for the original request, though it - was able to match part of the requested address. - You may wish to examine the original request for - misspellings and/or an incomplete address. - place_id (str): - The place ID for this result. - """ - - geocoder_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - intermediate_waypoint_request_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - type_: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - partial_match: bool = proto.Field( - proto.BOOL, - number=4, - ) - place_id: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py deleted file mode 100644 index 722cd7dda46a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Location', - }, -) - - -class Location(proto.Message): - r"""Encapsulates a location (a geographic point, and an optional - heading). - - Attributes: - lat_lng (google.type.latlng_pb2.LatLng): - The waypoint's geographic coordinates. - heading (google.protobuf.wrappers_pb2.Int32Value): - The compass heading associated with the direction of the - flow of traffic. This value is used to specify the side of - the road to use for pickup and drop-off. Heading values can - be from 0 to 360, where 0 specifies a heading of due North, - 90 specifies a heading of due East, etc. You can use this - field only for ``DRIVE`` and ``TWO_WHEELER`` travel modes. - """ - - lat_lng: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - heading: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py deleted file mode 100644 index 60e5cd3cb9c6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Maneuver', - }, -) - - -class Maneuver(proto.Enum): - r"""A set of values that specify the navigation action to take - for the current step (e.g., turn left, merge, straight, etc.). - - Values: - MANEUVER_UNSPECIFIED (0): - Not used. - TURN_SLIGHT_LEFT (1): - Turn slightly to the left. - TURN_SHARP_LEFT (2): - Turn sharply to the left. - UTURN_LEFT (3): - Make a left u-turn. - TURN_LEFT (4): - Turn left. - TURN_SLIGHT_RIGHT (5): - Turn slightly to the right. - TURN_SHARP_RIGHT (6): - Turn sharply to the right. - UTURN_RIGHT (7): - Make a right u-turn. - TURN_RIGHT (8): - Turn right. - STRAIGHT (9): - Go straight. - RAMP_LEFT (10): - Take the left ramp. - RAMP_RIGHT (11): - Take the right ramp. - MERGE (12): - Merge into traffic. - FORK_LEFT (13): - Take the left fork. - FORK_RIGHT (14): - Take the right fork. - FERRY (15): - Take the ferry. - FERRY_TRAIN (16): - Take the train leading onto the ferry. - ROUNDABOUT_LEFT (17): - Turn left at the roundabout. - ROUNDABOUT_RIGHT (18): - Turn right at the roundabout. - """ - MANEUVER_UNSPECIFIED = 0 - TURN_SLIGHT_LEFT = 1 - TURN_SHARP_LEFT = 2 - UTURN_LEFT = 3 - TURN_LEFT = 4 - TURN_SLIGHT_RIGHT = 5 - TURN_SHARP_RIGHT = 6 - UTURN_RIGHT = 7 - TURN_RIGHT = 8 - STRAIGHT = 9 - RAMP_LEFT = 10 - RAMP_RIGHT = 11 - MERGE = 12 - FORK_LEFT = 13 - FORK_RIGHT = 14 - FERRY = 15 - FERRY_TRAIN = 16 - ROUNDABOUT_LEFT = 17 - ROUNDABOUT_RIGHT = 18 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py deleted file mode 100644 index dc8b69e76ccd..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import maneuver as gmr_maneuver - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'NavigationInstruction', - }, -) - - -class NavigationInstruction(proto.Message): - r"""Encapsulates navigation instructions for a - [RouteLegStep][google.maps.routing.v2.RouteLegStep] - - Attributes: - maneuver (google.maps.routing_v2.types.Maneuver): - Encapsulates the navigation instructions for - the current step (e.g., turn left, merge, - straight, etc.). This field determines which - icon to display. - instructions (str): - Instructions for navigating this step. - """ - - maneuver: gmr_maneuver.Maneuver = proto.Field( - proto.ENUM, - number=1, - enum=gmr_maneuver.Maneuver, - ) - instructions: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py deleted file mode 100644 index 4d9630691288..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'PolylineQuality', - 'PolylineEncoding', - 'Polyline', - }, -) - - -class PolylineQuality(proto.Enum): - r"""A set of values that specify the quality of the polyline. - - Values: - POLYLINE_QUALITY_UNSPECIFIED (0): - No polyline quality preference specified. Defaults to - ``OVERVIEW``. - HIGH_QUALITY (1): - Specifies a high-quality polyline - which is composed using - more points than ``OVERVIEW``, at the cost of increased - response size. Use this value when you need more precision. - OVERVIEW (2): - Specifies an overview polyline - which is composed using a - small number of points. Use this value when displaying an - overview of the route. Using this option has a lower request - latency compared to using the ``HIGH_QUALITY`` option. - """ - POLYLINE_QUALITY_UNSPECIFIED = 0 - HIGH_QUALITY = 1 - OVERVIEW = 2 - - -class PolylineEncoding(proto.Enum): - r"""Specifies the preferred type of polyline to be returned. - - Values: - POLYLINE_ENCODING_UNSPECIFIED (0): - No polyline type preference specified. Defaults to - ``ENCODED_POLYLINE``. - ENCODED_POLYLINE (1): - Specifies a polyline encoded using the `polyline encoding - algorithm `__. - GEO_JSON_LINESTRING (2): - Specifies a polyline using the `GeoJSON LineString - format `__ - """ - POLYLINE_ENCODING_UNSPECIFIED = 0 - ENCODED_POLYLINE = 1 - GEO_JSON_LINESTRING = 2 - - -class Polyline(proto.Message): - r"""Encapsulates an encoded polyline. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - encoded_polyline (str): - The string encoding of the polyline using the `polyline - encoding - algorithm `__ - - This field is a member of `oneof`_ ``polyline_type``. - geo_json_linestring (google.protobuf.struct_pb2.Struct): - Specifies a polyline using the `GeoJSON LineString - format `__ - - This field is a member of `oneof`_ ``polyline_type``. - """ - - encoded_polyline: str = proto.Field( - proto.STRING, - number=1, - oneof='polyline_type', - ) - geo_json_linestring: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - oneof='polyline_type', - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py deleted file mode 100644 index 2a57054febff..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py +++ /dev/null @@ -1,409 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.geo.type import viewport_pb2 # type: ignore -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction -from google.maps.routing_v2.types import polyline as gmr_polyline -from google.maps.routing_v2.types import route_label -from google.maps.routing_v2.types import speed_reading_interval -from google.maps.routing_v2.types import toll_info as gmr_toll_info -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Route', - 'RouteTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteLegStepTravelAdvisory', - 'RouteLeg', - 'RouteLegStep', - }, -) - - -class Route(proto.Message): - r"""Encapsulates a route, which consists of a series of connected - road segments that join beginning, ending, and intermediate - waypoints. - - Attributes: - route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): - Labels for the ``Route`` that are useful to identify - specific properties of the route to compare against others. - legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): - A collection of legs (path segments between waypoints) that - make-up the route. Each leg corresponds to the trip between - two non-\ ``via`` Waypoints. For example, a route with no - intermediate waypoints has only one leg. A route that - includes one non-\ ``via`` intermediate waypoint has two - legs. A route that includes one ``via`` intermediate - waypoint has one leg. The order of the legs matches the - order of Waypoints from ``origin`` to ``intermediates`` to - ``destination``. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the route - without taking traffic conditions into - consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall route polyline. This polyline will be the - combined polyline of all ``legs``. - description (str): - A description of the route. - warnings (MutableSequence[str]): - An array of warnings to show when displaying - the route. - viewport (google.geo.type.viewport_pb2.Viewport): - The viewport bounding box of the polyline. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. - route_token (str): - Web-safe base64 encoded route token that can be passed to - NavigationSDK, which allows the Navigation SDK to - reconstruct the route during navigation, and in the event of - rerouting honor the original intention when Routes - ComputeRoutes is called. Customers should treat this token - as an opaque blob. NOTE: ``Route.route_token`` is only - available for requests that have set - ``ComputeRoutesRequest.routing_preference`` to - ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. - ``Route.route_token`` is also not supported for requests - that have Via waypoints. - """ - - route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( - proto.ENUM, - number=13, - enum=route_label.RouteLabel, - ) - legs: MutableSequence['RouteLeg'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteLeg', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=2, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_polyline.Polyline, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - warnings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - viewport: viewport_pb2.Viewport = proto.Field( - proto.MESSAGE, - number=8, - message=viewport_pb2.Viewport, - ) - travel_advisory: 'RouteTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=9, - message='RouteTravelAdvisory', - ) - route_token: str = proto.Field( - proto.STRING, - number=12, - ) - - -class RouteTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction - etc. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Encapsulates information about tolls on the Route. This - field is only populated if we expect there are tolls on the - Route. If this field is set but the estimated_price subfield - is not populated, we expect that road contains tolls but we - do not know an estimated price. If this field is not set, - then we expect there is no toll on the Route. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the route without overlap. The - start point of a specified interval is the same as the end - point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - fuel_consumption_microliters (int): - The fuel consumption prediction in - microliters. - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=speed_reading_interval.SpeedReadingInterval, - ) - fuel_consumption_microliters: int = proto.Field( - proto.INT64, - number=5, - ) - - -class RouteLegTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction - etc. on a route leg. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Encapsulates information about tolls on the specific - RouteLeg. This field is only populated if we expect there - are tolls on the RouteLeg. If this field is set but the - estimated_price subfield is not populated, we expect that - road contains tolls but we do not know an estimated price. - If this field does not exist, then there is no toll on the - RouteLeg. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the RouteLg without overlap. - The start point of a specified interval is the same as the - end point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLegStepTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction on - a leg step. - - Attributes: - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - NOTE: This field is not currently populated. - """ - - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLeg(proto.Message): - r"""Encapsulates a segment between non-\ ``via`` waypoints. - - Attributes: - distance_meters (int): - The travel distance of the route leg, in - meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the leg. If the - ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then - this value is the same as ``static_duration``. If the - ``route_preference`` is either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the leg, - calculated without taking traffic conditions - into consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall polyline for this leg. This includes that each - ``step``'s polyline. - start_location (google.maps.routing_v2.types.Location): - The start location of this leg. This might be different from - the provided ``origin``. For example, when the provided - ``origin`` is not near a road, this is a point on the road. - end_location (google.maps.routing_v2.types.Location): - The end location of this leg. This might be different from - the provided ``destination``. For example, when the provided - ``destination`` is not near a road, this is a point on the - road. - steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): - An array of steps denoting segments within - this leg. Each step represents one navigation - instruction. - travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): - Encapsulates the additional information that - the user should be informed about, such as - possible traffic zone restriction etc. on a - route leg. - """ - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=4, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=6, - message=location.Location, - ) - steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='RouteLegStep', - ) - travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=8, - message='RouteLegTravelAdvisory', - ) - - -class RouteLegStep(proto.Message): - r"""Encapsulates a segment of a ``RouteLeg``. A step corresponds to a - single navigation instruction. Route legs are made up of steps. - - Attributes: - distance_meters (int): - The travel distance of this step, in meters. - In some circumstances, this field might not have - a value. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of travel through this step - without taking traffic conditions into - consideration. In some circumstances, this field - might not have a value. - polyline (google.maps.routing_v2.types.Polyline): - The polyline associated with this step. - start_location (google.maps.routing_v2.types.Location): - The start location of this step. - end_location (google.maps.routing_v2.types.Location): - The end location of this step. - navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): - Navigation instructions. - travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): - Encapsulates the additional information that - the user should be informed about, such as - possible traffic zone restriction on a leg step. - """ - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=4, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( - proto.MESSAGE, - number=6, - message=gmr_navigation_instruction.NavigationInstruction, - ) - travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=7, - message='RouteLegStepTravelAdvisory', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py deleted file mode 100644 index a3e095209d58..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteLabel', - }, -) - - -class RouteLabel(proto.Enum): - r"""Labels for the ``Route`` that are useful to identify specific - properties of the route to compare against others. - - Values: - ROUTE_LABEL_UNSPECIFIED (0): - Default - not used. - DEFAULT_ROUTE (1): - The default "best" route returned for the - route computation. - DEFAULT_ROUTE_ALTERNATE (2): - An alternative to the default "best" route. Routes like this - will be returned when - ``ComputeRoutesRequest.compute_alternative_routes`` is - specified. - FUEL_EFFICIENT (3): - Fuel efficient route. Routes labeled with - this value are determined to be optimized for - Eco parameters such as fuel consumption. - """ - ROUTE_LABEL_UNSPECIFIED = 0 - DEFAULT_ROUTE = 1 - DEFAULT_ROUTE_ALTERNATE = 2 - FUEL_EFFICIENT = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py deleted file mode 100644 index 59f5e6420c4c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import toll_passes as gmr_toll_passes -from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteModifiers', - }, -) - - -class RouteModifiers(proto.Message): - r"""Encapsulates a set of optional conditions to satisfy when - calculating the routes. - - Attributes: - avoid_tolls (bool): - Specifies whether to avoid toll roads where reasonable. - Preference will be given to routes not containing toll - roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - travel modes. - avoid_highways (bool): - Specifies whether to avoid highways where reasonable. - Preference will be given to routes not containing highways. - Applies only to the ``DRIVE`` and ``TWO_WHEELER`` travel - modes. - avoid_ferries (bool): - Specifies whether to avoid ferries where reasonable. - Preference will be given to routes not containing travel by - ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` - travel modes. - avoid_indoor (bool): - Specifies whether to avoid navigating indoors where - reasonable. Preference will be given to routes not - containing indoor navigation. Applies only to the ``WALK`` - travel mode. - vehicle_info (google.maps.routing_v2.types.VehicleInfo): - Specifies the vehicle information. - toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): - Encapsulates information about toll passes. If toll passes - are provided, the API tries to return the pass price. If - toll passes are not provided, the API treats the toll pass - as unknown and tries to return the cash price. Applies only - to the DRIVE and TWO_WHEELER travel modes. - """ - - avoid_tolls: bool = proto.Field( - proto.BOOL, - number=1, - ) - avoid_highways: bool = proto.Field( - proto.BOOL, - number=2, - ) - avoid_ferries: bool = proto.Field( - proto.BOOL, - number=3, - ) - avoid_indoor: bool = proto.Field( - proto.BOOL, - number=4, - ) - vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_vehicle_info.VehicleInfo, - ) - toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( - proto.ENUM, - number=6, - enum=gmr_toll_passes.TollPass, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py deleted file mode 100644 index 14d466006fae..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteTravelMode', - }, -) - - -class RouteTravelMode(proto.Enum): - r"""A set of values used to specify the mode of travel. NOTE: WALK, - BICYCLE, and TWO_WHEELER routes are in beta and might sometimes be - missing clear sidewalks, pedestrian paths, or bicycling paths. You - must display this warning to the user for all walking, bicycling, - and two-wheel routes that you display in your app. - - Values: - TRAVEL_MODE_UNSPECIFIED (0): - No travel mode specified. Defaults to ``DRIVE``. - DRIVE (1): - Travel by passenger car. - BICYCLE (2): - Travel by bicycle. - WALK (3): - Travel by walking. - TWO_WHEELER (4): - Two-wheeled, motorized vehicle. For example, motorcycle. - Note that this differs from the ``BICYCLE`` travel mode - which covers human-powered mode. - """ - TRAVEL_MODE_UNSPECIFIED = 0 - DRIVE = 1 - BICYCLE = 2 - WALK = 3 - TWO_WHEELER = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py deleted file mode 100644 index dffc427d20a5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py +++ /dev/null @@ -1,512 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import fallback_info as gmr_fallback_info -from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routing_preference as gmr_routing_preference -from google.maps.routing_v2.types import units as gmr_units -from google.maps.routing_v2.types import waypoint as gmr_waypoint -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteMatrixElementCondition', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'ComputeRouteMatrixRequest', - 'RouteMatrixOrigin', - 'RouteMatrixDestination', - 'RouteMatrixElement', - }, -) - - -class RouteMatrixElementCondition(proto.Enum): - r"""The condition of the route being returned. - - Values: - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): - Only used when the ``status`` of the element is not OK. - ROUTE_EXISTS (1): - A route was found, and the corresponding - information was filled out for the element. - ROUTE_NOT_FOUND (2): - No route could be found. Fields containing route - information, such as ``distance_meters`` or ``duration``, - will not be filled out in the element. - """ - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 - ROUTE_EXISTS = 1 - ROUTE_NOT_FOUND = 2 - - -class ComputeRoutesRequest(proto.Message): - r"""ComputeRoutes request message. - - Attributes: - origin (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint. - destination (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint. - intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): - Optional. A set of waypoints along the route - (excluding terminal points), for either stopping - at or passing by. Up to 25 intermediate - waypoints are supported. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, then an error is returned. You can - specify this option only when the ``travel_mode`` is - ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. - polyline_quality (google.maps.routing_v2.types.PolylineQuality): - Optional. Specifies your preference for the - quality of the polyline. - polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): - Optional. Specifies the preferred encoding - for the polyline. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't - set this value, then this value defaults to the - time that you made the request. If you set this - value to a time that has already occurred, then - the request fails. - compute_alternative_routes (bool): - Optional. Specifies whether to calculate - alternate routes in addition to the route. No - alternative routes are returned for requests - that have intermediate waypoints. - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. A set of conditions to satisfy that - affect the way routes are calculated. - language_code (str): - Optional. The BCP-47 language code, such as "en-US" or - "sr-Latn". For more information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - See `Language - Support `__ - for the list of supported languages. When you don't provide - this value, the display language is inferred from the - location of the route request. - units (google.maps.routing_v2.types.Units): - Optional. Specifies the units of measure for the display - fields. This includes the ``instruction`` field in - ``NavigationInstruction``. The units of measure used for the - route, leg, step distance, and duration are not affected by - this value. If you don't provide this value, then the - display units are inferred from the location of the request. - requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): - Optional. Specifies what reference routes to calculate as - part of the request in addition to the default route. A - reference route is a route with a different route - calculation objective than the default route. For example an - FUEL_EFFICIENT reference route calculation takes into - account various parameters that would generate an optimal - fuel efficient route. - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - """ - class ReferenceRoute(proto.Enum): - r"""A supported reference route on the ComputeRoutesRequest. - - Values: - REFERENCE_ROUTE_UNSPECIFIED (0): - Not used. Requests containing this value - fail. - FUEL_EFFICIENT (1): - Fuel efficient route. Routes labeled with - this value are determined to be optimized for - parameters such as fuel consumption. - """ - REFERENCE_ROUTE_UNSPECIFIED = 0 - FUEL_EFFICIENT = 1 - - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the route(s). - FUEL_CONSUMPTION (2): - Estimated fuel consumption for the route(s). - TRAFFIC_ON_POLYLINE (3): - Traffic aware polylines for the route(s). - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - FUEL_CONSUMPTION = 2 - TRAFFIC_ON_POLYLINE = 3 - - origin: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - destination: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_waypoint.Waypoint, - ) - intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=gmr_waypoint.Waypoint, - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=4, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=5, - enum=gmr_routing_preference.RoutingPreference, - ) - polyline_quality: polyline.PolylineQuality = proto.Field( - proto.ENUM, - number=6, - enum=polyline.PolylineQuality, - ) - polyline_encoding: polyline.PolylineEncoding = proto.Field( - proto.ENUM, - number=12, - enum=polyline.PolylineEncoding, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - compute_alternative_routes: bool = proto.Field( - proto.BOOL, - number=8, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=9, - message=gmr_route_modifiers.RouteModifiers, - ) - language_code: str = proto.Field( - proto.STRING, - number=10, - ) - units: gmr_units.Units = proto.Field( - proto.ENUM, - number=11, - enum=gmr_units.Units, - ) - requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( - proto.ENUM, - number=14, - enum=ReferenceRoute, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=15, - enum=ExtraComputation, - ) - - -class ComputeRoutesResponse(proto.Message): - r"""ComputeRoutes the response message. - - Attributes: - routes (MutableSequence[google.maps.routing_v2.types.Route]): - Contains an array of computed routes (up to three) when you - specify compute_alternatives_routes, and contains just one - route when you don't. When this array contains multiple - entries, the first one is the most recommended route. If the - array is empty, then it means no route could be found. - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route results with all of the input - preferences, it may fallback to using a - different way of computation. When fallback mode - is used, this field contains detailed info about - the fallback response. Otherwise this field is - unset. - geocoding_results (google.maps.routing_v2.types.GeocodingResults): - Contains geocoding response info for - waypoints specified as addresses. - """ - - routes: MutableSequence[route.Route] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=route.Route, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_fallback_info.FallbackInfo, - ) - geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_geocoding_results.GeocodingResults, - ) - - -class ComputeRouteMatrixRequest(proto.Message): - r"""ComputeRouteMatrix request message - - Attributes: - origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): - Required. Array of origins, which determines the rows of the - response matrix. Several size restrictions apply to the - cardinality of origins and destinations: - - - The number of elements (origins × destinations) must be - no greater than 625 in any case. - - The number of elements (origins × destinations) must be - no greater than 100 if routing_preference is set to - ``TRAFFIC_AWARE_OPTIMAL``. - - The number of waypoints (origins + destinations) - specified as ``place_id`` must be no greater than 50. - destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): - Required. Array of destinations, which - determines the columns of the response matrix. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, an error is returned. You can specify - this option only when the ``travel_mode`` is ``DRIVE`` or - ``TWO_WHEELER``, otherwise the request fails. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't - set this value, this defaults to the time that - you made the request. If you set this value to a - time that has already occurred, the request - fails. - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - """ - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the matrix element(s). - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - - origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteMatrixOrigin', - ) - destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='RouteMatrixDestination', - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=3, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=4, - enum=gmr_routing_preference.RoutingPreference, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=8, - enum=ExtraComputation, - ) - - -class RouteMatrixOrigin(proto.Message): - r"""A single origin for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. Modifiers for every route that - takes this as the origin - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_route_modifiers.RouteModifiers, - ) - - -class RouteMatrixDestination(proto.Message): - r"""A single destination for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - - -class RouteMatrixElement(proto.Message): - r"""Encapsulates route information computed for an - origin/destination pair in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - origin_index (int): - Zero-based index of the origin in the - request. - - This field is a member of `oneof`_ ``_origin_index``. - destination_index (int): - Zero-based index of the destination in the - request. - - This field is a member of `oneof`_ ``_destination_index``. - status (google.rpc.status_pb2.Status): - Error status code for this element. - condition (google.maps.routing_v2.types.RouteMatrixElementCondition): - Indicates whether the route was found or not. - Independent of status. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the route - without taking traffic conditions into - consideration. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. For - example: restriction information and toll - information - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route with the given preferences for - this particular origin/destination pair, it may - fall back to using a different mode of - computation. When fallback mode is used, this - field contains detailed information about the - fallback response. Otherwise this field is - unset. - """ - - origin_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - destination_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - condition: 'RouteMatrixElementCondition' = proto.Field( - proto.ENUM, - number=9, - enum='RouteMatrixElementCondition', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=4, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - travel_advisory: route.RouteTravelAdvisory = proto.Field( - proto.MESSAGE, - number=7, - message=route.RouteTravelAdvisory, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=8, - message=gmr_fallback_info.FallbackInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py deleted file mode 100644 index d7d3a75786b1..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RoutingPreference', - }, -) - - -class RoutingPreference(proto.Enum): - r"""A set of values that specify factors to take into - consideration when calculating the route. - - Values: - ROUTING_PREFERENCE_UNSPECIFIED (0): - No routing preference specified. Default to - ``TRAFFIC_UNAWARE``. - TRAFFIC_UNAWARE (1): - Computes routes without taking live traffic conditions into - consideration. Suitable when traffic conditions don't matter - or are not applicable. Using this value produces the lowest - latency. Note: For ``RouteTravelMode`` DRIVE and TWO_WHEELER - choice of route and duration are based on road network and - average time-independent traffic conditions. Results for a - given request may vary over time due to changes in the road - network, updated average traffic conditions, and the - distributed nature of the service. Results may also vary - between nearly-equivalent routes at any time or frequency. - TRAFFIC_AWARE (2): - Calculates routes taking live traffic conditions into - consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, - some optimizations are applied to significantly reduce - latency. - TRAFFIC_AWARE_OPTIMAL (3): - Calculates the routes taking live traffic - conditions into consideration, without applying - most performance optimizations. Using this value - produces the highest latency. - """ - ROUTING_PREFERENCE_UNSPECIFIED = 0 - TRAFFIC_UNAWARE = 1 - TRAFFIC_AWARE = 2 - TRAFFIC_AWARE_OPTIMAL = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py deleted file mode 100644 index 9a322fff1e94..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'SpeedReadingInterval', - }, -) - - -class SpeedReadingInterval(proto.Message): - r"""Traffic density indicator on a contiguous segment of a polyline or - path. Given a path with points P_0, P_1, ... , P_N (zero-based - index), the SpeedReadingInterval defines an interval and describes - its traffic using the following categories. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - start_polyline_point_index (int): - The starting index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_start_polyline_point_index``. - end_polyline_point_index (int): - The ending index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_end_polyline_point_index``. - speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): - Traffic speed in this interval. - """ - class Speed(proto.Enum): - r"""The classification of polyline speed based on traffic data. - - Values: - SPEED_UNSPECIFIED (0): - Default value. This value is unused. - NORMAL (1): - Normal speed, no slowdown is detected. - SLOW (2): - Slowdown detected, but no traffic jam formed. - TRAFFIC_JAM (3): - Traffic jam detected. - """ - SPEED_UNSPECIFIED = 0 - NORMAL = 1 - SLOW = 2 - TRAFFIC_JAM = 3 - - start_polyline_point_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - end_polyline_point_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - speed: Speed = proto.Field( - proto.ENUM, - number=3, - enum=Speed, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py deleted file mode 100644 index 3182bd03ac01..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.type import money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TollInfo', - }, -) - - -class TollInfo(proto.Message): - r"""Encapsulates toll information on a ``Route`` or on a ``RouteLeg``. - - Attributes: - estimated_price (MutableSequence[google.type.money_pb2.Money]): - The monetary amount of tolls for the - corresponding Route or RouteLeg. This list - contains a money amount for each currency that - is expected to be charged by the toll stations. - Typically this list will contain only one item - for routes with tolls in one currency. For - international trips, this list may contain - multiple items to reflect tolls in different - currencies. - """ - - estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=money_pb2.Money, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py deleted file mode 100644 index 05edb1a082c3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py +++ /dev/null @@ -1,348 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TollPass', - }, -) - - -class TollPass(proto.Enum): - r"""List of toll passes around the world that we support. - - Values: - TOLL_PASS_UNSPECIFIED (0): - Not used. If this value is used, then the - request fails. - AU_ETOLL_TAG (82): - Sydney toll pass. See additional details at - https://www.myetoll.com.au. - AU_EWAY_TAG (83): - Sydney toll pass. See additional details at - https://www.tollpay.com.au. - AU_LINKT (2): - Australia-wide toll pass. - See additional details at - https://www.linkt.com.au/. - AR_TELEPASE (3): - Argentina toll pass. See additional details - at https://telepase.com.ar - BR_AUTO_EXPRESO (81): - Brazil toll pass. See additional details at - https://www.autoexpreso.com - BR_CONECTCAR (7): - Brazil toll pass. See additional details at - https://conectcar.com. - BR_MOVE_MAIS (8): - Brazil toll pass. See additional details at - https://movemais.com. - BR_PASSA_RAPIDO (88): - Brazil toll pass. See additional details at - https://pasorapido.gob.do/ - BR_SEM_PARAR (9): - Brazil toll pass. See additional details at - https://www.semparar.com.br. - BR_TAGGY (10): - Brazil toll pass. See additional details at - https://taggy.com.br. - BR_VELOE (11): - Brazil toll pass. See additional details at - https://veloe.com.br/site/onde-usar. - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): - Canada to United States border crossing. - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): - Canada to United States border crossing. - CA_US_BLUE_WATER_EDGE_PASS (18): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_CONNEXION (19): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_NEXUS_CARD (20): - Canada to United States border crossing. - ID_E_TOLL (16): - Indonesia. - E-card provided by multiple banks used to pay - for tolls. All e-cards via banks are charged the - same so only one enum value is needed. E.g. - - Bank Mandiri - https://www.bankmandiri.co.id/e-money - BCA - https://www.bca.co.id/flazz - - BNI - https://www.bni.co.id/id-id/ebanking/tapcash - IN_FASTAG (78): - India. - IN_LOCAL_HP_PLATE_EXEMPT (79): - India, HP state plate exemption. - MX_IAVE (90): - Mexico toll pass. - https://iave.capufe.gob.mx/#/ - MX_PASE (91): - Mexico - https://www.pase.com.mx - MX_QUICKPASS (93): - Mexico - https://operadoravial.com/quick-pass/ - MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): - http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf - MX_TAG_IAVE (12): - Mexico - MX_TAG_TELEVIA (13): - Mexico toll pass company. One of many - operating in Mexico City. See additional details - at https://www.televia.com.mx. - MX_TELEVIA (92): - Mexico toll pass company. One of many - operating in Mexico City. - https://www.televia.com.mx - MX_VIAPASS (14): - Mexico toll pass. See additional details at - https://www.viapass.com.mx/viapass/web_home.aspx. - US_AL_FREEDOM_PASS (21): - AL, USA. - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): - AK, USA. - US_CA_FASTRAK (4): - CA, USA. - US_CA_FASTRAK_CAV_STICKER (86): - Indicates driver has any FasTrak pass in - addition to the DMV issued Clean Air Vehicle - (CAV) sticker. - https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml - US_CO_EXPRESSTOLL (23): - CO, USA. - US_CO_GO_PASS (24): - CO, USA. - US_DE_EZPASSDE (25): - DE, USA. - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): - FL, USA. - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): - FL, USA. - US_FL_EPASS (67): - FL, USA. - US_FL_GIBA_TOLL_PASS (68): - FL, USA. - US_FL_LEEWAY (69): - FL, USA. - US_FL_SUNPASS (70): - FL, USA. - US_FL_SUNPASS_PRO (71): - FL, USA. - US_IL_EZPASSIL (73): - IL, USA. - US_IL_IPASS (72): - IL, USA. - US_IN_EZPASSIN (26): - IN, USA. - US_KS_BESTPASS_HORIZON (27): - KS, USA. - US_KS_KTAG (28): - KS, USA. - US_KS_NATIONALPASS (29): - KS, USA. - US_KS_PREPASS_ELITEPASS (30): - KS, USA. - US_KY_RIVERLINK (31): - KY, USA. - US_LA_GEAUXPASS (32): - LA, USA. - US_LA_TOLL_TAG (33): - LA, USA. - US_MA_EZPASSMA (6): - MA, USA. - US_MD_EZPASSMD (34): - MD, USA. - US_ME_EZPASSME (35): - ME, USA. - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): - MI, USA. - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): - MI, USA. - US_MI_IQ_PROX_CARD (38): - MI, USA. - US_MI_MACKINAC_BRIDGE_MAC_PASS (39): - MI, USA. - US_MI_NEXPRESS_TOLL (40): - MI, USA. - US_MN_EZPASSMN (41): - MN, USA. - US_NC_EZPASSNC (42): - NC, USA. - US_NC_PEACH_PASS (87): - NC, USA. - US_NC_QUICK_PASS (43): - NC, USA. - US_NH_EZPASSNH (80): - NH, USA. - US_NJ_DOWNBEACH_EXPRESS_PASS (75): - NJ, USA. - US_NJ_EZPASSNJ (74): - NJ, USA. - US_NY_EXPRESSPASS (76): - NY, USA. - US_NY_EZPASSNY (77): - NY, USA. - US_OH_EZPASSOH (44): - OH, USA. - US_PA_EZPASSPA (45): - PA, USA. - US_RI_EZPASSRI (46): - RI, USA. - US_SC_PALPASS (47): - SC, USA. - US_TX_BANCPASS (48): - TX, USA. - US_TX_DEL_RIO_PASS (49): - TX, USA. - US_TX_EFAST_PASS (50): - TX, USA. - US_TX_EAGLE_PASS_EXPRESS_CARD (51): - TX, USA. - US_TX_EPTOLL (52): - TX, USA. - US_TX_EZ_CROSS (53): - TX, USA. - US_TX_EZTAG (54): - TX, USA. - US_TX_LAREDO_TRADE_TAG (55): - TX, USA. - US_TX_PLUSPASS (56): - TX, USA. - US_TX_TOLLTAG (57): - TX, USA. - US_TX_TXTAG (58): - TX, USA. - US_TX_XPRESS_CARD (59): - TX, USA. - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): - UT, USA. - US_VA_EZPASSVA (61): - VA, USA. - US_WA_BREEZEBY (17): - WA, USA. - US_WA_GOOD_TO_GO (1): - WA, USA. - US_WV_EZPASSWV (62): - WV, USA. - US_WV_MEMORIAL_BRIDGE_TICKETS (63): - WV, USA. - US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): - WV, USA. - """ - TOLL_PASS_UNSPECIFIED = 0 - AU_ETOLL_TAG = 82 - AU_EWAY_TAG = 83 - AU_LINKT = 2 - AR_TELEPASE = 3 - BR_AUTO_EXPRESO = 81 - BR_CONECTCAR = 7 - BR_MOVE_MAIS = 8 - BR_PASSA_RAPIDO = 88 - BR_SEM_PARAR = 9 - BR_TAGGY = 10 - BR_VELOE = 11 - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 - CA_US_BLUE_WATER_EDGE_PASS = 18 - CA_US_CONNEXION = 19 - CA_US_NEXUS_CARD = 20 - ID_E_TOLL = 16 - IN_FASTAG = 78 - IN_LOCAL_HP_PLATE_EXEMPT = 79 - MX_IAVE = 90 - MX_PASE = 91 - MX_QUICKPASS = 93 - MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 - MX_TAG_IAVE = 12 - MX_TAG_TELEVIA = 13 - MX_TELEVIA = 92 - MX_VIAPASS = 14 - US_AL_FREEDOM_PASS = 21 - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 - US_CA_FASTRAK = 4 - US_CA_FASTRAK_CAV_STICKER = 86 - US_CO_EXPRESSTOLL = 23 - US_CO_GO_PASS = 24 - US_DE_EZPASSDE = 25 - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 - US_FL_EPASS = 67 - US_FL_GIBA_TOLL_PASS = 68 - US_FL_LEEWAY = 69 - US_FL_SUNPASS = 70 - US_FL_SUNPASS_PRO = 71 - US_IL_EZPASSIL = 73 - US_IL_IPASS = 72 - US_IN_EZPASSIN = 26 - US_KS_BESTPASS_HORIZON = 27 - US_KS_KTAG = 28 - US_KS_NATIONALPASS = 29 - US_KS_PREPASS_ELITEPASS = 30 - US_KY_RIVERLINK = 31 - US_LA_GEAUXPASS = 32 - US_LA_TOLL_TAG = 33 - US_MA_EZPASSMA = 6 - US_MD_EZPASSMD = 34 - US_ME_EZPASSME = 35 - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 - US_MI_IQ_PROX_CARD = 38 - US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 - US_MI_NEXPRESS_TOLL = 40 - US_MN_EZPASSMN = 41 - US_NC_EZPASSNC = 42 - US_NC_PEACH_PASS = 87 - US_NC_QUICK_PASS = 43 - US_NH_EZPASSNH = 80 - US_NJ_DOWNBEACH_EXPRESS_PASS = 75 - US_NJ_EZPASSNJ = 74 - US_NY_EXPRESSPASS = 76 - US_NY_EZPASSNY = 77 - US_OH_EZPASSOH = 44 - US_PA_EZPASSPA = 45 - US_RI_EZPASSRI = 46 - US_SC_PALPASS = 47 - US_TX_BANCPASS = 48 - US_TX_DEL_RIO_PASS = 49 - US_TX_EFAST_PASS = 50 - US_TX_EAGLE_PASS_EXPRESS_CARD = 51 - US_TX_EPTOLL = 52 - US_TX_EZ_CROSS = 53 - US_TX_EZTAG = 54 - US_TX_LAREDO_TRADE_TAG = 55 - US_TX_PLUSPASS = 56 - US_TX_TOLLTAG = 57 - US_TX_TXTAG = 58 - US_TX_XPRESS_CARD = 59 - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 - US_VA_EZPASSVA = 61 - US_WA_BREEZEBY = 17 - US_WA_GOOD_TO_GO = 1 - US_WV_EZPASSWV = 62 - US_WV_MEMORIAL_BRIDGE_TICKETS = 63 - US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py deleted file mode 100644 index 93cfaf1ee04c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Units', - }, -) - - -class Units(proto.Enum): - r"""A set of values that specify the unit of measure used in the - display. - - Values: - UNITS_UNSPECIFIED (0): - Units of measure not specified. Defaults to - the unit of measure inferred from the request. - METRIC (1): - Metric units of measure. - IMPERIAL (2): - Imperial (English) units of measure. - """ - UNITS_UNSPECIFIED = 0 - METRIC = 1 - IMPERIAL = 2 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py deleted file mode 100644 index a94a99025c80..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'VehicleEmissionType', - }, -) - - -class VehicleEmissionType(proto.Enum): - r"""A set of values describing the vehicle's emission type. - Applies only to the DRIVE travel mode. - - Values: - VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): - No emission type specified. Default to - GASOLINE. - GASOLINE (1): - Gasoline/petrol fueled vehicle. - ELECTRIC (2): - Electricity powered vehicle. - HYBRID (3): - Hybrid fuel (such as gasoline + electric) - vehicle. - DIESEL (4): - Diesel fueled vehicle. - """ - VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 - GASOLINE = 1 - ELECTRIC = 2 - HYBRID = 3 - DIESEL = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py deleted file mode 100644 index 2d71bb0a70a0..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import vehicle_emission_type - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'VehicleInfo', - }, -) - - -class VehicleInfo(proto.Message): - r"""Encapsulates the vehicle information, such as the license - plate last character. - - Attributes: - emission_type (google.maps.routing_v2.types.VehicleEmissionType): - Describes the vehicle's emission type. - Applies only to the DRIVE travel mode. - """ - - emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( - proto.ENUM, - number=2, - enum=vehicle_emission_type.VehicleEmissionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py deleted file mode 100644 index c25013cfd086..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import location as gmr_location - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Waypoint', - }, -) - - -class Waypoint(proto.Message): - r"""Encapsulates a waypoint. Waypoints mark both the beginning - and end of a route, and include intermediate stops along the - route. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - location (google.maps.routing_v2.types.Location): - A point specified using geographic - coordinates, including an optional heading. - - This field is a member of `oneof`_ ``location_type``. - place_id (str): - The POI Place ID associated with the - waypoint. - - This field is a member of `oneof`_ ``location_type``. - address (str): - Human readable address or a plus code. - See https://plus.codes for details. - - This field is a member of `oneof`_ ``location_type``. - via (bool): - Marks this waypoint as a milestone rather a stopping point. - For each non-via waypoint in the request, the response - appends an entry to the ``legs`` array to provide the - details for stopovers on that leg of the trip. Set this - value to true when you want the route to pass through this - waypoint without stopping over. Via waypoints don't cause an - entry to be added to the ``legs`` array, but they do route - the journey through the waypoint. You can only set this - value on waypoints that are intermediates. The request fails - if you set this field on terminal waypoints. If - ``ComputeRoutesRequest.optimize_waypoint_order`` is set to - true then this field cannot be set to true; otherwise, the - request fails. - vehicle_stopover (bool): - Indicates that the waypoint is meant for vehicles to stop - at, where the intention is to either pickup or drop-off. - When you set this value, the calculated route won't include - non-\ ``via`` waypoints on roads that are unsuitable for - pickup and drop-off. This option works only for ``DRIVE`` - and ``TWO_WHEELER`` travel modes, and when the - ``location_type`` is ``location``. - side_of_road (bool): - Indicates that the location of this waypoint is meant to - have a preference for the vehicle to stop at a particular - side of road. When you set this value, the route will pass - through the location so that the vehicle can stop at the - side of road that the location is biased towards from the - center of the road. This option works only for 'DRIVE' and - 'TWO_WHEELER' travel modes. - """ - - location: gmr_location.Location = proto.Field( - proto.MESSAGE, - number=1, - oneof='location_type', - message=gmr_location.Location, - ) - place_id: str = proto.Field( - proto.STRING, - number=2, - oneof='location_type', - ) - address: str = proto.Field( - proto.STRING, - number=7, - oneof='location_type', - ) - via: bool = proto.Field( - proto.BOOL, - number=3, - ) - vehicle_stopover: bool = proto.Field( - proto.BOOL, - number=4, - ) - side_of_road: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py deleted file mode 100644 index 59757e684c85..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/routing_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py deleted file mode 100644 index 381f53f7a26e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py deleted file mode 100644 index 125691404b0b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py deleted file mode 100644 index c978c3e55cd7..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py deleted file mode 100644 index ca13730e4ddc..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json deleted file mode 100644 index b5ed5aca319c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json +++ /dev/null @@ -1,321 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.routing.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-maps-routing", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_route_matrix_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_route_matrix_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_routes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_routes_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py deleted file mode 100644 index 291c4ea93db5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class routingCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'extra_computations', ), - 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'units', 'requested_reference_routes', 'extra_computations', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=routingCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the routing client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py deleted file mode 100644 index b93d9d947fd8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-maps-routing' - - -description = "Google Maps Routing API client library" - -version = {} -with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "google-geo-type >= 0.1.0, <1.0.0dev", -] -url = "https://github.com/googleapis/python-maps-routing" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.maps"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt deleted file mode 100644 index 33ac865954a6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 -google-geo-type==0.1.0 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py deleted file mode 100644 index 55f7b3a4ba31..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py +++ /dev/null @@ -1,1750 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.maps.routing_v2.services.routes import RoutesAsyncClient -from google.maps.routing_v2.services.routes import RoutesClient -from google.maps.routing_v2.services.routes import transports -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routes_service -from google.maps.routing_v2.types import routing_preference -from google.maps.routing_v2.types import toll_passes -from google.maps.routing_v2.types import units -from google.maps.routing_v2.types import vehicle_emission_type -from google.maps.routing_v2.types import vehicle_info -from google.maps.routing_v2.types import waypoint -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -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 RoutesClient._get_default_mtls_endpoint(None) is None - assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RoutesGrpcTransport, "grpc"), - (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RoutesRestTransport, "rest"), -]) -def test_routes_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -def test_routes_client_get_transport_class(): - transport = RoutesClient.get_transport_class() - available_transports = [ - transports.RoutesGrpcTransport, - transports.RoutesRestTransport, - ] - assert transport in available_transports - - transport = RoutesClient.get_transport_class("grpc") - assert transport == transports.RoutesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -def test_routes_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RoutesClient, transports.RoutesRestTransport, "rest", "true"), - (RoutesClient, transports.RoutesRestTransport, "rest", "false"), -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_routes_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - RoutesClient, RoutesAsyncClient -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -def test_routes_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -def test_routes_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RoutesClient, transports.RoutesRestTransport, "rest", None), -]) -def test_routes_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_routes_client_client_options_from_dict(): - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RoutesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_routes_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "routes.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes(request_type, transport: str = 'grpc'): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = routes_service.ComputeRoutesResponse( - ) - response = client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - client.compute_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - -@pytest.mark.asyncio -async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( - )) - response = await client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -@pytest.mark.asyncio -async def test_compute_routes_async_from_dict(): - await test_compute_routes_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix(request_type, transport: str = 'grpc'): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([routes_service.RouteMatrixElement()]) - response = client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, routes_service.RouteMatrixElement) - - -def test_compute_route_matrix_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - client.compute_route_matrix() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - -@pytest.mark.asyncio -async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) - response = await client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, routes_service.RouteMatrixElement) - - -@pytest.mark.asyncio -async def test_compute_route_matrix_async_from_dict(): - await test_compute_route_matrix_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes_rest(request_type): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = routes_service.ComputeRoutesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.compute_routes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): - transport_class = transports.RoutesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.ComputeRoutesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.compute_routes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_routes_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_routes._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_routes_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) - - request = routes_service.ComputeRoutesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.ComputeRoutesResponse() - - client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compute_routes_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRoutesRequest): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.compute_routes(request) - - -def test_compute_routes_rest_error(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix_rest(request_type): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = routes_service.RouteMatrixElement( - origin_index=1279, - destination_index=1817, - condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, - distance_meters=1594, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - json_return_value = "[{}]".format(json_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.compute_route_matrix(request) - - assert isinstance(response, Iterable) - response = next(response) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.RouteMatrixElement) - assert response.origin_index == 1279 - assert response.destination_index == 1817 - assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS - assert response.distance_meters == 1594 - - -def test_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): - transport_class = transports.RoutesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.RouteMatrixElement() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - json_return_value = "[{}]".format(json_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.compute_route_matrix(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_route_matrix_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_route_matrix_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) - req.return_value._content = "[{}]".format(req.return_value._content) - - request = routes_service.ComputeRouteMatrixRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.RouteMatrixElement() - - client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compute_route_matrix_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.compute_route_matrix(request) - - -def test_compute_route_matrix_rest_error(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RoutesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RoutesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = RoutesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RoutesGrpcTransport, - ) - -def test_routes_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_routes_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'compute_routes', - 'compute_route_matrix', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_routes_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -def test_routes_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport() - adc.assert_called_once() - - -def test_routes_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - RoutesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - ], -) -def test_routes_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, - ], -) -def test_routes_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.RoutesGrpcTransport, grpc_helpers), - (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_routes_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "routes.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_routes_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.RoutesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_routes_host_no_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_routes_host_with_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_routes_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RoutesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RoutesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.compute_routes._session - session2 = client2.transport.compute_routes._session - assert session1 != session2 - session1 = client1.transport.compute_route_matrix._session - session2 = client2.transport.compute_route_matrix._session - assert session1 != session2 -def test_routes_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_routes_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - 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 - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - 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=cred, - credentials_file=None, - scopes=None, - 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 - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_transport_channel_mtls_with_adc( - transport_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), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - 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 - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RoutesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = RoutesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = RoutesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = RoutesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RoutesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = RoutesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = RoutesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = RoutesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RoutesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = RoutesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: - transport_class = RoutesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (RoutesClient, transports.RoutesGrpcTransport), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/packages/google-maps-routing/setup.py b/packages/google-maps-routing/setup.py index bedb432b4c3a..80774eef6672 100644 --- a/packages/google-maps-routing/setup.py +++ b/packages/google-maps-routing/setup.py @@ -40,6 +40,7 @@ "proto-plus >= 1.22.0, <2.0.0dev", "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "google-geo-type >= 0.1.0, <1.0.0dev", ] url = "https://github.com/googleapis/google-cloud-python" diff --git a/packages/google-maps-routing/testing/constraints-3.10.txt b/packages/google-maps-routing/testing/constraints-3.10.txt index ed7f9aed2559..2214a366a259 100644 --- a/packages/google-maps-routing/testing/constraints-3.10.txt +++ b/packages/google-maps-routing/testing/constraints-3.10.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +google-geo-type diff --git a/packages/google-maps-routing/testing/constraints-3.11.txt b/packages/google-maps-routing/testing/constraints-3.11.txt index ed7f9aed2559..2214a366a259 100644 --- a/packages/google-maps-routing/testing/constraints-3.11.txt +++ b/packages/google-maps-routing/testing/constraints-3.11.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +google-geo-type diff --git a/packages/google-maps-routing/testing/constraints-3.12.txt b/packages/google-maps-routing/testing/constraints-3.12.txt index ed7f9aed2559..2214a366a259 100644 --- a/packages/google-maps-routing/testing/constraints-3.12.txt +++ b/packages/google-maps-routing/testing/constraints-3.12.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +google-geo-type diff --git a/packages/google-maps-routing/testing/constraints-3.7.txt b/packages/google-maps-routing/testing/constraints-3.7.txt index 6c44adfea7ee..33ac865954a6 100644 --- a/packages/google-maps-routing/testing/constraints-3.7.txt +++ b/packages/google-maps-routing/testing/constraints-3.7.txt @@ -7,3 +7,4 @@ google-api-core==1.34.0 proto-plus==1.22.0 protobuf==3.19.5 +google-geo-type==0.1.0 diff --git a/packages/google-maps-routing/testing/constraints-3.8.txt b/packages/google-maps-routing/testing/constraints-3.8.txt index ed7f9aed2559..2214a366a259 100644 --- a/packages/google-maps-routing/testing/constraints-3.8.txt +++ b/packages/google-maps-routing/testing/constraints-3.8.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +google-geo-type diff --git a/packages/google-maps-routing/testing/constraints-3.9.txt b/packages/google-maps-routing/testing/constraints-3.9.txt index ed7f9aed2559..2214a366a259 100644 --- a/packages/google-maps-routing/testing/constraints-3.9.txt +++ b/packages/google-maps-routing/testing/constraints-3.9.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +google-geo-type From 3edeaaa42419042294e74fd030cdbae47642eb09 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 17 Mar 2023 22:49:36 +0000 Subject: [PATCH 07/12] feat: adds support for specifying region_code in the ComputeRoutesRequest feat: adds support for specifying region_code and language_code in the ComputeRouteMatrixRequest PiperOrigin-RevId: 517493769 Source-Link: https://github.com/googleapis/googleapis/commit/8fa8ae4c7610d3cc2e265c464106abb2ce1e8716 Source-Link: https://github.com/googleapis/googleapis-gen/commit/45fd970b1a158937dea5554d5b5ee4ccf5db780f Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcm91dGluZy8uT3dsQm90LnlhbWwiLCJoIjoiNDVmZDk3MGIxYTE1ODkzN2RlYTU1NTRkNWI1ZWU0Y2NmNWRiNzgwZiJ9 --- .../google-maps-routing/v2/.coveragerc | 13 + .../google-maps-routing/v2/.flake8 | 33 + .../google-maps-routing/v2/MANIFEST.in | 2 + .../google-maps-routing/v2/README.rst | 49 + .../google-maps-routing/v2/docs/conf.py | 376 ++++ .../google-maps-routing/v2/docs/index.rst | 7 + .../v2/docs/routing_v2/routes.rst | 6 + .../v2/docs/routing_v2/services.rst | 6 + .../v2/docs/routing_v2/types.rst | 6 + .../v2/google/maps/routing/__init__.py | 97 + .../v2/google/maps/routing/gapic_version.py | 16 + .../v2/google/maps/routing/py.typed | 2 + .../v2/google/maps/routing_v2/__init__.py | 98 + .../maps/routing_v2/gapic_metadata.json | 58 + .../google/maps/routing_v2/gapic_version.py | 16 + .../v2/google/maps/routing_v2/py.typed | 2 + .../maps/routing_v2/services/__init__.py | 15 + .../routing_v2/services/routes/__init__.py | 22 + .../services/routes/async_client.py | 416 ++++ .../maps/routing_v2/services/routes/client.py | 613 ++++++ .../services/routes/transports/__init__.py | 38 + .../services/routes/transports/base.py | 161 ++ .../services/routes/transports/grpc.py | 363 ++++ .../routes/transports/grpc_asyncio.py | 362 ++++ .../services/routes/transports/rest.py | 417 ++++ .../google/maps/routing_v2/types/__init__.py | 105 + .../maps/routing_v2/types/fallback_info.py | 103 + .../routing_v2/types/geocoding_results.py | 125 ++ .../google/maps/routing_v2/types/location.py | 62 + .../google/maps/routing_v2/types/maneuver.py | 96 + .../types/navigation_instruction.py | 58 + .../google/maps/routing_v2/types/polyline.py | 113 ++ .../v2/google/maps/routing_v2/types/route.py | 409 ++++ .../maps/routing_v2/types/route_label.py | 57 + .../maps/routing_v2/types/route_modifiers.py | 97 + .../routing_v2/types/route_travel_mode.py | 59 + .../maps/routing_v2/types/routes_service.py | 541 +++++ .../routing_v2/types/routing_preference.py | 67 + .../types/speed_reading_interval.py | 89 + .../google/maps/routing_v2/types/toll_info.py | 56 + .../maps/routing_v2/types/toll_passes.py | 348 ++++ .../v2/google/maps/routing_v2/types/units.py | 49 + .../routing_v2/types/vehicle_emission_type.py | 56 + .../maps/routing_v2/types/vehicle_info.py | 50 + .../google/maps/routing_v2/types/waypoint.py | 123 ++ .../google-maps-routing/v2/mypy.ini | 3 + .../google-maps-routing/v2/noxfile.py | 184 ++ ...rated_routes_compute_route_matrix_async.py | 52 + ...erated_routes_compute_route_matrix_sync.py | 52 + ...2_generated_routes_compute_routes_async.py | 51 + ...v2_generated_routes_compute_routes_sync.py | 51 + ...ippet_metadata_google.maps.routing.v2.json | 321 +++ .../v2/scripts/fixup_routing_v2_keywords.py | 177 ++ .../google-maps-routing/v2/setup.py | 91 + .../v2/testing/constraints-3.10.txt | 7 + .../v2/testing/constraints-3.11.txt | 7 + .../v2/testing/constraints-3.12.txt | 7 + .../v2/testing/constraints-3.7.txt | 10 + .../v2/testing/constraints-3.8.txt | 7 + .../v2/testing/constraints-3.9.txt | 7 + .../google-maps-routing/v2/tests/__init__.py | 16 + .../v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/routing_v2/__init__.py | 16 + .../unit/gapic/routing_v2/test_routes.py | 1750 +++++++++++++++++ 65 files changed, 8698 insertions(+) create mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc create mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 create mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py create mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini create mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json create mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py create mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py diff --git a/owl-bot-staging/google-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc new file mode 100644 index 000000000000..d0ce5597b0a9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/routing/__init__.py + google/maps/routing/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.flake8 @@ -0,0 +1,33 @@ +# -*- 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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in new file mode 100644 index 000000000000..c5b56c111c00 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/routing *.py +recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst new file mode 100644 index 000000000000..f0002366e552 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Routing API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Maps Routing API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py new file mode 100644 index 000000000000..d7a10abed96b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-maps-routing documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +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"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-maps-routing" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# 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"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# 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 + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +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 = { + "description": "Google Maps Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# 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 + +# 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 + +# 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, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# 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 = [] + +# 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' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is 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 = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# 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' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# 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' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-maps-routing-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- 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', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-maps-routing.tex", + u"google-maps-routing 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 + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# 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 = [ + ( + root_doc, + "google-maps-routing", + u"Google Maps Routing Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-maps-routing", + u"google-maps-routing Documentation", + author, + "google-maps-routing", + "GAPIC library for Google Maps Routing API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# 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), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst new file mode 100644 index 000000000000..e2563dd88ee9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + routing_v2/services + routing_v2/types diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst new file mode 100644 index 000000000000..3d52309cddae --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst @@ -0,0 +1,6 @@ +Routes +------------------------ + +.. automodule:: google.maps.routing_v2.services.routes + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst new file mode 100644 index 000000000000..e96568dc434c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst @@ -0,0 +1,6 @@ +Services for Google Maps Routing v2 API +======================================= +.. toctree:: + :maxdepth: 2 + + routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst new file mode 100644 index 000000000000..176a5a812cf8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst @@ -0,0 +1,6 @@ +Types for Google Maps Routing v2 API +==================================== + +.. automodule:: google.maps.routing_v2.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py new file mode 100644 index 000000000000..59020a3484c3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.maps.routing import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.routing_v2.services.routes.client import RoutesClient +from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient + +from google.maps.routing_v2.types.fallback_info import FallbackInfo +from google.maps.routing_v2.types.fallback_info import FallbackReason +from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode +from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint +from google.maps.routing_v2.types.geocoding_results import GeocodingResults +from google.maps.routing_v2.types.location import Location +from google.maps.routing_v2.types.maneuver import Maneuver +from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction +from google.maps.routing_v2.types.polyline import Polyline +from google.maps.routing_v2.types.polyline import PolylineEncoding +from google.maps.routing_v2.types.polyline import PolylineQuality +from google.maps.routing_v2.types.route import Route +from google.maps.routing_v2.types.route import RouteLeg +from google.maps.routing_v2.types.route import RouteLegStep +from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory +from google.maps.routing_v2.types.route import RouteLegTravelAdvisory +from google.maps.routing_v2.types.route import RouteTravelAdvisory +from google.maps.routing_v2.types.route_label import RouteLabel +from google.maps.routing_v2.types.route_modifiers import RouteModifiers +from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode +from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse +from google.maps.routing_v2.types.routes_service import RouteMatrixDestination +from google.maps.routing_v2.types.routes_service import RouteMatrixElement +from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin +from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition +from google.maps.routing_v2.types.routing_preference import RoutingPreference +from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval +from google.maps.routing_v2.types.toll_info import TollInfo +from google.maps.routing_v2.types.toll_passes import TollPass +from google.maps.routing_v2.types.units import Units +from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType +from google.maps.routing_v2.types.vehicle_info import VehicleInfo +from google.maps.routing_v2.types.waypoint import Waypoint + +__all__ = ('RoutesClient', + 'RoutesAsyncClient', + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py new file mode 100644 index 000000000000..405b1cebcf15 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py new file mode 100644 index 000000000000..cd9d694f63c6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.maps.routing_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.routes import RoutesClient +from .services.routes import RoutesAsyncClient + +from .types.fallback_info import FallbackInfo +from .types.fallback_info import FallbackReason +from .types.fallback_info import FallbackRoutingMode +from .types.geocoding_results import GeocodedWaypoint +from .types.geocoding_results import GeocodingResults +from .types.location import Location +from .types.maneuver import Maneuver +from .types.navigation_instruction import NavigationInstruction +from .types.polyline import Polyline +from .types.polyline import PolylineEncoding +from .types.polyline import PolylineQuality +from .types.route import Route +from .types.route import RouteLeg +from .types.route import RouteLegStep +from .types.route import RouteLegStepTravelAdvisory +from .types.route import RouteLegTravelAdvisory +from .types.route import RouteTravelAdvisory +from .types.route_label import RouteLabel +from .types.route_modifiers import RouteModifiers +from .types.route_travel_mode import RouteTravelMode +from .types.routes_service import ComputeRouteMatrixRequest +from .types.routes_service import ComputeRoutesRequest +from .types.routes_service import ComputeRoutesResponse +from .types.routes_service import RouteMatrixDestination +from .types.routes_service import RouteMatrixElement +from .types.routes_service import RouteMatrixOrigin +from .types.routes_service import RouteMatrixElementCondition +from .types.routing_preference import RoutingPreference +from .types.speed_reading_interval import SpeedReadingInterval +from .types.toll_info import TollInfo +from .types.toll_passes import TollPass +from .types.units import Units +from .types.vehicle_emission_type import VehicleEmissionType +from .types.vehicle_info import VehicleInfo +from .types.waypoint import Waypoint + +__all__ = ( + 'RoutesAsyncClient', +'ComputeRouteMatrixRequest', +'ComputeRoutesRequest', +'ComputeRoutesResponse', +'FallbackInfo', +'FallbackReason', +'FallbackRoutingMode', +'GeocodedWaypoint', +'GeocodingResults', +'Location', +'Maneuver', +'NavigationInstruction', +'Polyline', +'PolylineEncoding', +'PolylineQuality', +'Route', +'RouteLabel', +'RouteLeg', +'RouteLegStep', +'RouteLegStepTravelAdvisory', +'RouteLegTravelAdvisory', +'RouteMatrixDestination', +'RouteMatrixElement', +'RouteMatrixElementCondition', +'RouteMatrixOrigin', +'RouteModifiers', +'RouteTravelAdvisory', +'RouteTravelMode', +'RoutesClient', +'RoutingPreference', +'SpeedReadingInterval', +'TollInfo', +'TollPass', +'Units', +'VehicleEmissionType', +'VehicleInfo', +'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json new file mode 100644 index 000000000000..8382cea1d39a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json @@ -0,0 +1,58 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.routing_v2", + "protoPackage": "google.maps.routing.v2", + "schema": "1.0", + "services": { + "Routes": { + "clients": { + "grpc": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RoutesAsyncClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "rest": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py new file mode 100644 index 000000000000..405b1cebcf15 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py new file mode 100644 index 000000000000..e8e1c3845db5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py new file mode 100644 index 000000000000..ff3f8f71863f --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RoutesClient +from .async_client import RoutesAsyncClient + +__all__ = ( + 'RoutesClient', + 'RoutesAsyncClient', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py new file mode 100644 index 000000000000..7f8df74a140b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union + +from google.maps.routing_v2 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .client import RoutesClient + + +class RoutesAsyncClient: + """The Routes API.""" + + _client: RoutesClient + + DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RoutesClient.common_folder_path) + parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) + common_organization_path = staticmethod(RoutesClient.common_organization_path) + parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) + common_project_path = staticmethod(RoutesClient.common_project_path) + parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) + common_location_path = staticmethod(RoutesClient.common_location_path) + parse_common_location_path = staticmethod(RoutesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(RoutesClient).get_transport_class, type(RoutesClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RoutesTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RoutesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RoutesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # Create or coerce a protobuf request object. + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compute_routes, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + # Create or coerce a protobuf request object. + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compute_route_matrix, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RoutesAsyncClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py new file mode 100644 index 000000000000..1943383c7246 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py @@ -0,0 +1,613 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast + +from google.maps.routing_v2 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RoutesGrpcTransport +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .transports.rest import RoutesRestTransport + + +class RoutesClientMeta(type): + """Metaclass for the Routes client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] + _transport_registry["grpc"] = RoutesGrpcTransport + _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport + _transport_registry["rest"] = RoutesRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RoutesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RoutesClient(metaclass=RoutesClientMeta): + """The Routes API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "routes.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RoutesTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, RoutesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RoutesTransport): + # transport is a RoutesTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a routes_service.ComputeRoutesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, routes_service.ComputeRoutesRequest): + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_routes] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[routes_service.RouteMatrixElement]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.maps.routing_v2.types.RouteMatrixElement]: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a routes_service.ComputeRouteMatrixRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, routes_service.ComputeRouteMatrixRequest): + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RoutesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RoutesClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py new file mode 100644 index 000000000000..a15967f001c9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RoutesTransport +from .grpc import RoutesGrpcTransport +from .grpc_asyncio import RoutesGrpcAsyncIOTransport +from .rest import RoutesRestTransport +from .rest import RoutesRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] +_transport_registry['grpc'] = RoutesGrpcTransport +_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport +_transport_registry['rest'] = RoutesRestTransport + +__all__ = ( + 'RoutesTransport', + 'RoutesGrpcTransport', + 'RoutesGrpcAsyncIOTransport', + 'RoutesRestTransport', + 'RoutesRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py new file mode 100644 index 000000000000..a6fa68993eca --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.maps.routing_v2 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.maps.routing_v2.types import routes_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class RoutesTransport(abc.ABC): + """Abstract transport class for Routes.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'routes.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.compute_routes: gapic_v1.method.wrap_method( + self.compute_routes, + default_timeout=None, + client_info=client_info, + ), + self.compute_route_matrix: gapic_v1.method.wrap_method( + self.compute_route_matrix, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Union[ + routes_service.ComputeRoutesResponse, + Awaitable[routes_service.ComputeRoutesResponse] + ]]: + raise NotImplementedError() + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Union[ + routes_service.RouteMatrixElement, + Awaitable[routes_service.RouteMatrixElement] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RoutesTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py new file mode 100644 index 000000000000..8316c8b03587 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py @@ -0,0 +1,363 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO + + +class RoutesGrpcTransport(RoutesTransport): + """gRPC backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + ~.ComputeRoutesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self.grpc_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + ~.RouteMatrixElement]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RoutesGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py new file mode 100644 index 000000000000..752c5eaefc33 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO +from .grpc import RoutesGrpcTransport + + +class RoutesGrpcAsyncIOTransport(RoutesTransport): + """gRPC AsyncIO backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Awaitable[routes_service.ComputeRoutesResponse]]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + Awaitable[~.ComputeRoutesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self.grpc_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Awaitable[routes_service.RouteMatrixElement]]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + Awaitable[~.RouteMatrixElement]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'RoutesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py new file mode 100644 index 000000000000..c7fdf524b0c7 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.maps.routing_v2.types import routes_service + +from .base import RoutesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RoutesRestInterceptor: + """Interceptor for Routes. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RoutesRestTransport. + + .. code-block:: python + class MyCustomRoutesInterceptor(RoutesRestInterceptor): + def pre_compute_route_matrix(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_route_matrix(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_compute_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_routes(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) + client = RoutesClient(transport=transport) + + + """ + def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: + """Post-rpc interceptor for compute_routes + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RoutesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RoutesRestInterceptor + + +class RoutesRestTransport(RoutesTransport): + """REST backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[RoutesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RoutesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ComputeRouteMatrix(RoutesRestStub): + def __hash__(self): + return hash("ComputeRouteMatrix") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: routes_service.ComputeRouteMatrixRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + r"""Call the compute route matrix method over HTTP. + + Args: + request (~.routes_service.ComputeRouteMatrixRequest): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.routes_service.RouteMatrixElement: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/distanceMatrix/v2:computeRouteMatrix', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) + pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) + resp = self._interceptor.post_compute_route_matrix(resp) + return resp + + class _ComputeRoutes(RoutesRestStub): + def __hash__(self): + return hash("ComputeRoutes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: routes_service.ComputeRoutesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> routes_service.ComputeRoutesResponse: + r"""Call the compute routes method over HTTP. + + Args: + request (~.routes_service.ComputeRoutesRequest): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.routes_service.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/directions/v2:computeRoutes', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_compute_routes(request, metadata) + pb_request = routes_service.ComputeRoutesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = routes_service.ComputeRoutesResponse() + pb_resp = routes_service.ComputeRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_compute_routes(resp) + return resp + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RoutesRestTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py new file mode 100644 index 000000000000..7323899cfc30 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .fallback_info import ( + FallbackInfo, + FallbackReason, + FallbackRoutingMode, +) +from .geocoding_results import ( + GeocodedWaypoint, + GeocodingResults, +) +from .location import ( + Location, +) +from .navigation_instruction import ( + NavigationInstruction, +) +from .polyline import ( + Polyline, + PolylineEncoding, + PolylineQuality, +) +from .route import ( + Route, + RouteLeg, + RouteLegStep, + RouteLegStepTravelAdvisory, + RouteLegTravelAdvisory, + RouteTravelAdvisory, +) +from .route_modifiers import ( + RouteModifiers, +) +from .routes_service import ( + ComputeRouteMatrixRequest, + ComputeRoutesRequest, + ComputeRoutesResponse, + RouteMatrixDestination, + RouteMatrixElement, + RouteMatrixOrigin, + RouteMatrixElementCondition, +) +from .speed_reading_interval import ( + SpeedReadingInterval, +) +from .toll_info import ( + TollInfo, +) +from .vehicle_info import ( + VehicleInfo, +) +from .waypoint import ( + Waypoint, +) + +__all__ = ( + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py new file mode 100644 index 000000000000..99670aafac25 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'FallbackReason', + 'FallbackRoutingMode', + 'FallbackInfo', + }, +) + + +class FallbackReason(proto.Enum): + r"""Reasons for using fallback response. + + Values: + FALLBACK_REASON_UNSPECIFIED (0): + No fallback reason specified. + SERVER_ERROR (1): + A server error happened while calculating + routes with your preferred routing mode, but we + were able to return a result calculated by an + alternative mode. + LATENCY_EXCEEDED (2): + We were not able to finish the calculation + with your preferred routing mode on time, but we + were able to return a result calculated by an + alternative mode. + """ + FALLBACK_REASON_UNSPECIFIED = 0 + SERVER_ERROR = 1 + LATENCY_EXCEEDED = 2 + + +class FallbackRoutingMode(proto.Enum): + r"""Actual routing mode used for returned fallback response. + + Values: + FALLBACK_ROUTING_MODE_UNSPECIFIED (0): + Not used. + FALLBACK_TRAFFIC_UNAWARE (1): + Indicates the "TRAFFIC_UNAWARE" routing mode was used to + compute the response. + FALLBACK_TRAFFIC_AWARE (2): + Indicates the "TRAFFIC_AWARE" routing mode was used to + compute the response. + """ + FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 + FALLBACK_TRAFFIC_UNAWARE = 1 + FALLBACK_TRAFFIC_AWARE = 2 + + +class FallbackInfo(proto.Message): + r"""Information related to how and why a fallback result was + used. If this field is set, then it means the server used a + different routing mode from your preferred mode as fallback. + + Attributes: + routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): + Routing mode used for the response. If + fallback was triggered, the mode may be + different from routing preference set in the + original client request. + reason (google.maps.routing_v2.types.FallbackReason): + The reason why fallback response was used + instead of the original response. This field is + only populated when the fallback mode is + triggered and the fallback response is returned. + """ + + routing_mode: 'FallbackRoutingMode' = proto.Field( + proto.ENUM, + number=1, + enum='FallbackRoutingMode', + ) + reason: 'FallbackReason' = proto.Field( + proto.ENUM, + number=2, + enum='FallbackReason', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py new file mode 100644 index 000000000000..ffa385a59a75 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'GeocodingResults', + 'GeocodedWaypoint', + }, +) + + +class GeocodingResults(proto.Message): + r"""Contains GeocodedWaypoints for origin, destination and + intermediate waypoints. Only populated for address waypoints. + + Attributes: + origin (google.maps.routing_v2.types.GeocodedWaypoint): + Origin geocoded waypoint. + destination (google.maps.routing_v2.types.GeocodedWaypoint): + Destination geocoded waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.GeocodedWaypoint]): + A list of intermediate geocoded waypoints + each containing an index field that corresponds + to the zero-based position of the waypoint in + the order they were specified in the request. + """ + + origin: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=1, + message='GeocodedWaypoint', + ) + destination: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=2, + message='GeocodedWaypoint', + ) + intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='GeocodedWaypoint', + ) + + +class GeocodedWaypoint(proto.Message): + r"""Details about the locations used as waypoints. Only populated + for address waypoints. Includes details about the geocoding + results for the purposes of determining what the address was + geocoded to. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + geocoder_status (google.rpc.status_pb2.Status): + Indicates the status code resulting from the + geocoding operation. + intermediate_waypoint_request_index (int): + The index of the corresponding intermediate + waypoint in the request. Only populated if the + corresponding waypoint is an intermediate + waypoint. + + This field is a member of `oneof`_ ``_intermediate_waypoint_request_index``. + type_ (MutableSequence[str]): + The type(s) of the result, in the form of + zero or more type tags. Supported types: + https://developers.google.com/maps/documentation/geocoding/requests-geocoding#Types + partial_match (bool): + Indicates that the geocoder did not return an + exact match for the original request, though it + was able to match part of the requested address. + You may wish to examine the original request for + misspellings and/or an incomplete address. + place_id (str): + The place ID for this result. + """ + + geocoder_status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + intermediate_waypoint_request_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + type_: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + partial_match: bool = proto.Field( + proto.BOOL, + number=4, + ) + place_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py new file mode 100644 index 000000000000..722cd7dda46a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Location', + }, +) + + +class Location(proto.Message): + r"""Encapsulates a location (a geographic point, and an optional + heading). + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + The waypoint's geographic coordinates. + heading (google.protobuf.wrappers_pb2.Int32Value): + The compass heading associated with the direction of the + flow of traffic. This value is used to specify the side of + the road to use for pickup and drop-off. Heading values can + be from 0 to 360, where 0 specifies a heading of due North, + 90 specifies a heading of due East, etc. You can use this + field only for ``DRIVE`` and ``TWO_WHEELER`` travel modes. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + heading: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py new file mode 100644 index 000000000000..60e5cd3cb9c6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Maneuver', + }, +) + + +class Maneuver(proto.Enum): + r"""A set of values that specify the navigation action to take + for the current step (e.g., turn left, merge, straight, etc.). + + Values: + MANEUVER_UNSPECIFIED (0): + Not used. + TURN_SLIGHT_LEFT (1): + Turn slightly to the left. + TURN_SHARP_LEFT (2): + Turn sharply to the left. + UTURN_LEFT (3): + Make a left u-turn. + TURN_LEFT (4): + Turn left. + TURN_SLIGHT_RIGHT (5): + Turn slightly to the right. + TURN_SHARP_RIGHT (6): + Turn sharply to the right. + UTURN_RIGHT (7): + Make a right u-turn. + TURN_RIGHT (8): + Turn right. + STRAIGHT (9): + Go straight. + RAMP_LEFT (10): + Take the left ramp. + RAMP_RIGHT (11): + Take the right ramp. + MERGE (12): + Merge into traffic. + FORK_LEFT (13): + Take the left fork. + FORK_RIGHT (14): + Take the right fork. + FERRY (15): + Take the ferry. + FERRY_TRAIN (16): + Take the train leading onto the ferry. + ROUNDABOUT_LEFT (17): + Turn left at the roundabout. + ROUNDABOUT_RIGHT (18): + Turn right at the roundabout. + """ + MANEUVER_UNSPECIFIED = 0 + TURN_SLIGHT_LEFT = 1 + TURN_SHARP_LEFT = 2 + UTURN_LEFT = 3 + TURN_LEFT = 4 + TURN_SLIGHT_RIGHT = 5 + TURN_SHARP_RIGHT = 6 + UTURN_RIGHT = 7 + TURN_RIGHT = 8 + STRAIGHT = 9 + RAMP_LEFT = 10 + RAMP_RIGHT = 11 + MERGE = 12 + FORK_LEFT = 13 + FORK_RIGHT = 14 + FERRY = 15 + FERRY_TRAIN = 16 + ROUNDABOUT_LEFT = 17 + ROUNDABOUT_RIGHT = 18 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py new file mode 100644 index 000000000000..dc8b69e76ccd --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import maneuver as gmr_maneuver + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'NavigationInstruction', + }, +) + + +class NavigationInstruction(proto.Message): + r"""Encapsulates navigation instructions for a + [RouteLegStep][google.maps.routing.v2.RouteLegStep] + + Attributes: + maneuver (google.maps.routing_v2.types.Maneuver): + Encapsulates the navigation instructions for + the current step (e.g., turn left, merge, + straight, etc.). This field determines which + icon to display. + instructions (str): + Instructions for navigating this step. + """ + + maneuver: gmr_maneuver.Maneuver = proto.Field( + proto.ENUM, + number=1, + enum=gmr_maneuver.Maneuver, + ) + instructions: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py new file mode 100644 index 000000000000..4d9630691288 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'PolylineQuality', + 'PolylineEncoding', + 'Polyline', + }, +) + + +class PolylineQuality(proto.Enum): + r"""A set of values that specify the quality of the polyline. + + Values: + POLYLINE_QUALITY_UNSPECIFIED (0): + No polyline quality preference specified. Defaults to + ``OVERVIEW``. + HIGH_QUALITY (1): + Specifies a high-quality polyline - which is composed using + more points than ``OVERVIEW``, at the cost of increased + response size. Use this value when you need more precision. + OVERVIEW (2): + Specifies an overview polyline - which is composed using a + small number of points. Use this value when displaying an + overview of the route. Using this option has a lower request + latency compared to using the ``HIGH_QUALITY`` option. + """ + POLYLINE_QUALITY_UNSPECIFIED = 0 + HIGH_QUALITY = 1 + OVERVIEW = 2 + + +class PolylineEncoding(proto.Enum): + r"""Specifies the preferred type of polyline to be returned. + + Values: + POLYLINE_ENCODING_UNSPECIFIED (0): + No polyline type preference specified. Defaults to + ``ENCODED_POLYLINE``. + ENCODED_POLYLINE (1): + Specifies a polyline encoded using the `polyline encoding + algorithm `__. + GEO_JSON_LINESTRING (2): + Specifies a polyline using the `GeoJSON LineString + format `__ + """ + POLYLINE_ENCODING_UNSPECIFIED = 0 + ENCODED_POLYLINE = 1 + GEO_JSON_LINESTRING = 2 + + +class Polyline(proto.Message): + r"""Encapsulates an encoded polyline. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + encoded_polyline (str): + The string encoding of the polyline using the `polyline + encoding + algorithm `__ + + This field is a member of `oneof`_ ``polyline_type``. + geo_json_linestring (google.protobuf.struct_pb2.Struct): + Specifies a polyline using the `GeoJSON LineString + format `__ + + This field is a member of `oneof`_ ``polyline_type``. + """ + + encoded_polyline: str = proto.Field( + proto.STRING, + number=1, + oneof='polyline_type', + ) + geo_json_linestring: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + oneof='polyline_type', + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py new file mode 100644 index 000000000000..2a57054febff --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py @@ -0,0 +1,409 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.geo.type import viewport_pb2 # type: ignore +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction +from google.maps.routing_v2.types import polyline as gmr_polyline +from google.maps.routing_v2.types import route_label +from google.maps.routing_v2.types import speed_reading_interval +from google.maps.routing_v2.types import toll_info as gmr_toll_info +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Route', + 'RouteTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteLegStepTravelAdvisory', + 'RouteLeg', + 'RouteLegStep', + }, +) + + +class Route(proto.Message): + r"""Encapsulates a route, which consists of a series of connected + road segments that join beginning, ending, and intermediate + waypoints. + + Attributes: + route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): + Labels for the ``Route`` that are useful to identify + specific properties of the route to compare against others. + legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): + A collection of legs (path segments between waypoints) that + make-up the route. Each leg corresponds to the trip between + two non-\ ``via`` Waypoints. For example, a route with no + intermediate waypoints has only one leg. A route that + includes one non-\ ``via`` intermediate waypoint has two + legs. A route that includes one ``via`` intermediate + waypoint has one leg. The order of the legs matches the + order of Waypoints from ``origin`` to ``intermediates`` to + ``destination``. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this + value is the same as ``static_duration``. If you set the + ``routing_preference`` to either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the route + without taking traffic conditions into + consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall route polyline. This polyline will be the + combined polyline of all ``legs``. + description (str): + A description of the route. + warnings (MutableSequence[str]): + An array of warnings to show when displaying + the route. + viewport (google.geo.type.viewport_pb2.Viewport): + The viewport bounding box of the polyline. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. + route_token (str): + Web-safe base64 encoded route token that can be passed to + NavigationSDK, which allows the Navigation SDK to + reconstruct the route during navigation, and in the event of + rerouting honor the original intention when Routes + ComputeRoutes is called. Customers should treat this token + as an opaque blob. NOTE: ``Route.route_token`` is only + available for requests that have set + ``ComputeRoutesRequest.routing_preference`` to + ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. + ``Route.route_token`` is also not supported for requests + that have Via waypoints. + """ + + route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( + proto.ENUM, + number=13, + enum=route_label.RouteLabel, + ) + legs: MutableSequence['RouteLeg'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteLeg', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=2, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_polyline.Polyline, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + warnings: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + viewport: viewport_pb2.Viewport = proto.Field( + proto.MESSAGE, + number=8, + message=viewport_pb2.Viewport, + ) + travel_advisory: 'RouteTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=9, + message='RouteTravelAdvisory', + ) + route_token: str = proto.Field( + proto.STRING, + number=12, + ) + + +class RouteTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction + etc. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Encapsulates information about tolls on the Route. This + field is only populated if we expect there are tolls on the + Route. If this field is set but the estimated_price subfield + is not populated, we expect that road contains tolls but we + do not know an estimated price. If this field is not set, + then we expect there is no toll on the Route. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the route without overlap. The + start point of a specified interval is the same as the end + point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + fuel_consumption_microliters (int): + The fuel consumption prediction in + microliters. + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=speed_reading_interval.SpeedReadingInterval, + ) + fuel_consumption_microliters: int = proto.Field( + proto.INT64, + number=5, + ) + + +class RouteLegTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction + etc. on a route leg. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Encapsulates information about tolls on the specific + RouteLeg. This field is only populated if we expect there + are tolls on the RouteLeg. If this field is set but the + estimated_price subfield is not populated, we expect that + road contains tolls but we do not know an estimated price. + If this field does not exist, then there is no toll on the + RouteLeg. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the RouteLg without overlap. + The start point of a specified interval is the same as the + end point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLegStepTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction on + a leg step. + + Attributes: + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + NOTE: This field is not currently populated. + """ + + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLeg(proto.Message): + r"""Encapsulates a segment between non-\ ``via`` waypoints. + + Attributes: + distance_meters (int): + The travel distance of the route leg, in + meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the leg. If the + ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then + this value is the same as ``static_duration``. If the + ``route_preference`` is either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the leg, + calculated without taking traffic conditions + into consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall polyline for this leg. This includes that each + ``step``'s polyline. + start_location (google.maps.routing_v2.types.Location): + The start location of this leg. This might be different from + the provided ``origin``. For example, when the provided + ``origin`` is not near a road, this is a point on the road. + end_location (google.maps.routing_v2.types.Location): + The end location of this leg. This might be different from + the provided ``destination``. For example, when the provided + ``destination`` is not near a road, this is a point on the + road. + steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): + An array of steps denoting segments within + this leg. Each step represents one navigation + instruction. + travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): + Encapsulates the additional information that + the user should be informed about, such as + possible traffic zone restriction etc. on a + route leg. + """ + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=4, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=6, + message=location.Location, + ) + steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='RouteLegStep', + ) + travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=8, + message='RouteLegTravelAdvisory', + ) + + +class RouteLegStep(proto.Message): + r"""Encapsulates a segment of a ``RouteLeg``. A step corresponds to a + single navigation instruction. Route legs are made up of steps. + + Attributes: + distance_meters (int): + The travel distance of this step, in meters. + In some circumstances, this field might not have + a value. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of travel through this step + without taking traffic conditions into + consideration. In some circumstances, this field + might not have a value. + polyline (google.maps.routing_v2.types.Polyline): + The polyline associated with this step. + start_location (google.maps.routing_v2.types.Location): + The start location of this step. + end_location (google.maps.routing_v2.types.Location): + The end location of this step. + navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): + Navigation instructions. + travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): + Encapsulates the additional information that + the user should be informed about, such as + possible traffic zone restriction on a leg step. + """ + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=4, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( + proto.MESSAGE, + number=6, + message=gmr_navigation_instruction.NavigationInstruction, + ) + travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=7, + message='RouteLegStepTravelAdvisory', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py new file mode 100644 index 000000000000..a3e095209d58 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteLabel', + }, +) + + +class RouteLabel(proto.Enum): + r"""Labels for the ``Route`` that are useful to identify specific + properties of the route to compare against others. + + Values: + ROUTE_LABEL_UNSPECIFIED (0): + Default - not used. + DEFAULT_ROUTE (1): + The default "best" route returned for the + route computation. + DEFAULT_ROUTE_ALTERNATE (2): + An alternative to the default "best" route. Routes like this + will be returned when + ``ComputeRoutesRequest.compute_alternative_routes`` is + specified. + FUEL_EFFICIENT (3): + Fuel efficient route. Routes labeled with + this value are determined to be optimized for + Eco parameters such as fuel consumption. + """ + ROUTE_LABEL_UNSPECIFIED = 0 + DEFAULT_ROUTE = 1 + DEFAULT_ROUTE_ALTERNATE = 2 + FUEL_EFFICIENT = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py new file mode 100644 index 000000000000..59f5e6420c4c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import toll_passes as gmr_toll_passes +from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteModifiers', + }, +) + + +class RouteModifiers(proto.Message): + r"""Encapsulates a set of optional conditions to satisfy when + calculating the routes. + + Attributes: + avoid_tolls (bool): + Specifies whether to avoid toll roads where reasonable. + Preference will be given to routes not containing toll + roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` + travel modes. + avoid_highways (bool): + Specifies whether to avoid highways where reasonable. + Preference will be given to routes not containing highways. + Applies only to the ``DRIVE`` and ``TWO_WHEELER`` travel + modes. + avoid_ferries (bool): + Specifies whether to avoid ferries where reasonable. + Preference will be given to routes not containing travel by + ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` + travel modes. + avoid_indoor (bool): + Specifies whether to avoid navigating indoors where + reasonable. Preference will be given to routes not + containing indoor navigation. Applies only to the ``WALK`` + travel mode. + vehicle_info (google.maps.routing_v2.types.VehicleInfo): + Specifies the vehicle information. + toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): + Encapsulates information about toll passes. If toll passes + are provided, the API tries to return the pass price. If + toll passes are not provided, the API treats the toll pass + as unknown and tries to return the cash price. Applies only + to the DRIVE and TWO_WHEELER travel modes. + """ + + avoid_tolls: bool = proto.Field( + proto.BOOL, + number=1, + ) + avoid_highways: bool = proto.Field( + proto.BOOL, + number=2, + ) + avoid_ferries: bool = proto.Field( + proto.BOOL, + number=3, + ) + avoid_indoor: bool = proto.Field( + proto.BOOL, + number=4, + ) + vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_vehicle_info.VehicleInfo, + ) + toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( + proto.ENUM, + number=6, + enum=gmr_toll_passes.TollPass, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py new file mode 100644 index 000000000000..14d466006fae --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteTravelMode', + }, +) + + +class RouteTravelMode(proto.Enum): + r"""A set of values used to specify the mode of travel. NOTE: WALK, + BICYCLE, and TWO_WHEELER routes are in beta and might sometimes be + missing clear sidewalks, pedestrian paths, or bicycling paths. You + must display this warning to the user for all walking, bicycling, + and two-wheel routes that you display in your app. + + Values: + TRAVEL_MODE_UNSPECIFIED (0): + No travel mode specified. Defaults to ``DRIVE``. + DRIVE (1): + Travel by passenger car. + BICYCLE (2): + Travel by bicycle. + WALK (3): + Travel by walking. + TWO_WHEELER (4): + Two-wheeled, motorized vehicle. For example, motorcycle. + Note that this differs from the ``BICYCLE`` travel mode + which covers human-powered mode. + """ + TRAVEL_MODE_UNSPECIFIED = 0 + DRIVE = 1 + BICYCLE = 2 + WALK = 3 + TWO_WHEELER = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py new file mode 100644 index 000000000000..b0dc2a6a0879 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py @@ -0,0 +1,541 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import fallback_info as gmr_fallback_info +from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routing_preference as gmr_routing_preference +from google.maps.routing_v2.types import units as gmr_units +from google.maps.routing_v2.types import waypoint as gmr_waypoint +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteMatrixElementCondition', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'ComputeRouteMatrixRequest', + 'RouteMatrixOrigin', + 'RouteMatrixDestination', + 'RouteMatrixElement', + }, +) + + +class RouteMatrixElementCondition(proto.Enum): + r"""The condition of the route being returned. + + Values: + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): + Only used when the ``status`` of the element is not OK. + ROUTE_EXISTS (1): + A route was found, and the corresponding + information was filled out for the element. + ROUTE_NOT_FOUND (2): + No route could be found. Fields containing route + information, such as ``distance_meters`` or ``duration``, + will not be filled out in the element. + """ + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 + ROUTE_EXISTS = 1 + ROUTE_NOT_FOUND = 2 + + +class ComputeRoutesRequest(proto.Message): + r"""ComputeRoutes request message. + + Attributes: + origin (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint. + destination (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): + Optional. A set of waypoints along the route + (excluding terminal points), for either stopping + at or passing by. Up to 25 intermediate + waypoints are supported. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, then an error is returned. You can + specify this option only when the ``travel_mode`` is + ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. + polyline_quality (google.maps.routing_v2.types.PolylineQuality): + Optional. Specifies your preference for the + quality of the polyline. + polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): + Optional. Specifies the preferred encoding + for the polyline. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't + set this value, then this value defaults to the + time that you made the request. If you set this + value to a time that has already occurred, then + the request fails. + compute_alternative_routes (bool): + Optional. Specifies whether to calculate + alternate routes in addition to the route. No + alternative routes are returned for requests + that have intermediate waypoints. + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. A set of conditions to satisfy that + affect the way routes are calculated. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + See `Language + Support `__ + for the list of supported languages. When you don't provide + this value, the display language is inferred from the + location of the route request. + region_code (str): + Optional. The region code, specified as a ccTLD ("top-level + domain") two-character value. For more information see + https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains + units (google.maps.routing_v2.types.Units): + Optional. Specifies the units of measure for the display + fields. This includes the ``instruction`` field in + ``NavigationInstruction``. The units of measure used for the + route, leg, step distance, and duration are not affected by + this value. If you don't provide this value, then the + display units are inferred from the location of the request. + requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): + Optional. Specifies what reference routes to calculate as + part of the request in addition to the default route. A + reference route is a route with a different route + calculation objective than the default route. For example an + FUEL_EFFICIENT reference route calculation takes into + account various parameters that would generate an optimal + fuel efficient route. + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + """ + class ReferenceRoute(proto.Enum): + r"""A supported reference route on the ComputeRoutesRequest. + + Values: + REFERENCE_ROUTE_UNSPECIFIED (0): + Not used. Requests containing this value + fail. + FUEL_EFFICIENT (1): + Fuel efficient route. Routes labeled with + this value are determined to be optimized for + parameters such as fuel consumption. + """ + REFERENCE_ROUTE_UNSPECIFIED = 0 + FUEL_EFFICIENT = 1 + + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the route(s). + FUEL_CONSUMPTION (2): + Estimated fuel consumption for the route(s). + TRAFFIC_ON_POLYLINE (3): + Traffic aware polylines for the route(s). + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + FUEL_CONSUMPTION = 2 + TRAFFIC_ON_POLYLINE = 3 + + origin: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + destination: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_waypoint.Waypoint, + ) + intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=gmr_waypoint.Waypoint, + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=4, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=5, + enum=gmr_routing_preference.RoutingPreference, + ) + polyline_quality: polyline.PolylineQuality = proto.Field( + proto.ENUM, + number=6, + enum=polyline.PolylineQuality, + ) + polyline_encoding: polyline.PolylineEncoding = proto.Field( + proto.ENUM, + number=12, + enum=polyline.PolylineEncoding, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + compute_alternative_routes: bool = proto.Field( + proto.BOOL, + number=8, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=9, + message=gmr_route_modifiers.RouteModifiers, + ) + language_code: str = proto.Field( + proto.STRING, + number=10, + ) + region_code: str = proto.Field( + proto.STRING, + number=16, + ) + units: gmr_units.Units = proto.Field( + proto.ENUM, + number=11, + enum=gmr_units.Units, + ) + requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( + proto.ENUM, + number=14, + enum=ReferenceRoute, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=15, + enum=ExtraComputation, + ) + + +class ComputeRoutesResponse(proto.Message): + r"""ComputeRoutes the response message. + + Attributes: + routes (MutableSequence[google.maps.routing_v2.types.Route]): + Contains an array of computed routes (up to three) when you + specify compute_alternatives_routes, and contains just one + route when you don't. When this array contains multiple + entries, the first one is the most recommended route. If the + array is empty, then it means no route could be found. + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route results with all of the input + preferences, it may fallback to using a + different way of computation. When fallback mode + is used, this field contains detailed info about + the fallback response. Otherwise this field is + unset. + geocoding_results (google.maps.routing_v2.types.GeocodingResults): + Contains geocoding response info for + waypoints specified as addresses. + """ + + routes: MutableSequence[route.Route] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=route.Route, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_fallback_info.FallbackInfo, + ) + geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_geocoding_results.GeocodingResults, + ) + + +class ComputeRouteMatrixRequest(proto.Message): + r"""ComputeRouteMatrix request message + + Attributes: + origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): + Required. Array of origins, which determines the rows of the + response matrix. Several size restrictions apply to the + cardinality of origins and destinations: + + - The number of elements (origins × destinations) must be + no greater than 625 in any case. + - The number of elements (origins × destinations) must be + no greater than 100 if routing_preference is set to + ``TRAFFIC_AWARE_OPTIMAL``. + - The number of waypoints (origins + destinations) + specified as ``place_id`` must be no greater than 50. + destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): + Required. Array of destinations, which + determines the columns of the response matrix. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, an error is returned. You can specify + this option only when the ``travel_mode`` is ``DRIVE`` or + ``TWO_WHEELER``, otherwise the request fails. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't + set this value, this defaults to the time that + you made the request. If you set this value to a + time that has already occurred, the request + fails. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + See `Language + Support `__ + for the list of supported languages. When you don't provide + this value, the display language is inferred from the + location of the first origin. + region_code (str): + Optional. The region code, specified as a ccTLD ("top-level + domain") two-character value. For more information see + https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + """ + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the matrix element(s). + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + + origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteMatrixOrigin', + ) + destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='RouteMatrixDestination', + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=3, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=4, + enum=gmr_routing_preference.RoutingPreference, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + region_code: str = proto.Field( + proto.STRING, + number=9, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=ExtraComputation, + ) + + +class RouteMatrixOrigin(proto.Message): + r"""A single origin for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. Modifiers for every route that + takes this as the origin + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_route_modifiers.RouteModifiers, + ) + + +class RouteMatrixDestination(proto.Message): + r"""A single destination for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + + +class RouteMatrixElement(proto.Message): + r"""Encapsulates route information computed for an + origin/destination pair in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + origin_index (int): + Zero-based index of the origin in the + request. + + This field is a member of `oneof`_ ``_origin_index``. + destination_index (int): + Zero-based index of the destination in the + request. + + This field is a member of `oneof`_ ``_destination_index``. + status (google.rpc.status_pb2.Status): + Error status code for this element. + condition (google.maps.routing_v2.types.RouteMatrixElementCondition): + Indicates whether the route was found or not. + Independent of status. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this + value is the same as ``static_duration``. If you set the + ``routing_preference`` to either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the route + without taking traffic conditions into + consideration. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. For + example: restriction information and toll + information + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route with the given preferences for + this particular origin/destination pair, it may + fall back to using a different mode of + computation. When fallback mode is used, this + field contains detailed information about the + fallback response. Otherwise this field is + unset. + """ + + origin_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + destination_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + condition: 'RouteMatrixElementCondition' = proto.Field( + proto.ENUM, + number=9, + enum='RouteMatrixElementCondition', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=4, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + travel_advisory: route.RouteTravelAdvisory = proto.Field( + proto.MESSAGE, + number=7, + message=route.RouteTravelAdvisory, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=8, + message=gmr_fallback_info.FallbackInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py new file mode 100644 index 000000000000..d7d3a75786b1 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RoutingPreference', + }, +) + + +class RoutingPreference(proto.Enum): + r"""A set of values that specify factors to take into + consideration when calculating the route. + + Values: + ROUTING_PREFERENCE_UNSPECIFIED (0): + No routing preference specified. Default to + ``TRAFFIC_UNAWARE``. + TRAFFIC_UNAWARE (1): + Computes routes without taking live traffic conditions into + consideration. Suitable when traffic conditions don't matter + or are not applicable. Using this value produces the lowest + latency. Note: For ``RouteTravelMode`` DRIVE and TWO_WHEELER + choice of route and duration are based on road network and + average time-independent traffic conditions. Results for a + given request may vary over time due to changes in the road + network, updated average traffic conditions, and the + distributed nature of the service. Results may also vary + between nearly-equivalent routes at any time or frequency. + TRAFFIC_AWARE (2): + Calculates routes taking live traffic conditions into + consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, + some optimizations are applied to significantly reduce + latency. + TRAFFIC_AWARE_OPTIMAL (3): + Calculates the routes taking live traffic + conditions into consideration, without applying + most performance optimizations. Using this value + produces the highest latency. + """ + ROUTING_PREFERENCE_UNSPECIFIED = 0 + TRAFFIC_UNAWARE = 1 + TRAFFIC_AWARE = 2 + TRAFFIC_AWARE_OPTIMAL = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py new file mode 100644 index 000000000000..9a322fff1e94 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'SpeedReadingInterval', + }, +) + + +class SpeedReadingInterval(proto.Message): + r"""Traffic density indicator on a contiguous segment of a polyline or + path. Given a path with points P_0, P_1, ... , P_N (zero-based + index), the SpeedReadingInterval defines an interval and describes + its traffic using the following categories. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_polyline_point_index (int): + The starting index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_start_polyline_point_index``. + end_polyline_point_index (int): + The ending index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_end_polyline_point_index``. + speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): + Traffic speed in this interval. + """ + class Speed(proto.Enum): + r"""The classification of polyline speed based on traffic data. + + Values: + SPEED_UNSPECIFIED (0): + Default value. This value is unused. + NORMAL (1): + Normal speed, no slowdown is detected. + SLOW (2): + Slowdown detected, but no traffic jam formed. + TRAFFIC_JAM (3): + Traffic jam detected. + """ + SPEED_UNSPECIFIED = 0 + NORMAL = 1 + SLOW = 2 + TRAFFIC_JAM = 3 + + start_polyline_point_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + end_polyline_point_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + speed: Speed = proto.Field( + proto.ENUM, + number=3, + enum=Speed, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py new file mode 100644 index 000000000000..3182bd03ac01 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.type import money_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TollInfo', + }, +) + + +class TollInfo(proto.Message): + r"""Encapsulates toll information on a ``Route`` or on a ``RouteLeg``. + + Attributes: + estimated_price (MutableSequence[google.type.money_pb2.Money]): + The monetary amount of tolls for the + corresponding Route or RouteLeg. This list + contains a money amount for each currency that + is expected to be charged by the toll stations. + Typically this list will contain only one item + for routes with tolls in one currency. For + international trips, this list may contain + multiple items to reflect tolls in different + currencies. + """ + + estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=money_pb2.Money, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py new file mode 100644 index 000000000000..05edb1a082c3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py @@ -0,0 +1,348 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TollPass', + }, +) + + +class TollPass(proto.Enum): + r"""List of toll passes around the world that we support. + + Values: + TOLL_PASS_UNSPECIFIED (0): + Not used. If this value is used, then the + request fails. + AU_ETOLL_TAG (82): + Sydney toll pass. See additional details at + https://www.myetoll.com.au. + AU_EWAY_TAG (83): + Sydney toll pass. See additional details at + https://www.tollpay.com.au. + AU_LINKT (2): + Australia-wide toll pass. + See additional details at + https://www.linkt.com.au/. + AR_TELEPASE (3): + Argentina toll pass. See additional details + at https://telepase.com.ar + BR_AUTO_EXPRESO (81): + Brazil toll pass. See additional details at + https://www.autoexpreso.com + BR_CONECTCAR (7): + Brazil toll pass. See additional details at + https://conectcar.com. + BR_MOVE_MAIS (8): + Brazil toll pass. See additional details at + https://movemais.com. + BR_PASSA_RAPIDO (88): + Brazil toll pass. See additional details at + https://pasorapido.gob.do/ + BR_SEM_PARAR (9): + Brazil toll pass. See additional details at + https://www.semparar.com.br. + BR_TAGGY (10): + Brazil toll pass. See additional details at + https://taggy.com.br. + BR_VELOE (11): + Brazil toll pass. See additional details at + https://veloe.com.br/site/onde-usar. + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): + Canada to United States border crossing. + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): + Canada to United States border crossing. + CA_US_BLUE_WATER_EDGE_PASS (18): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_CONNEXION (19): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_NEXUS_CARD (20): + Canada to United States border crossing. + ID_E_TOLL (16): + Indonesia. + E-card provided by multiple banks used to pay + for tolls. All e-cards via banks are charged the + same so only one enum value is needed. E.g. - + Bank Mandiri + https://www.bankmandiri.co.id/e-money - BCA + https://www.bca.co.id/flazz + - BNI + https://www.bni.co.id/id-id/ebanking/tapcash + IN_FASTAG (78): + India. + IN_LOCAL_HP_PLATE_EXEMPT (79): + India, HP state plate exemption. + MX_IAVE (90): + Mexico toll pass. + https://iave.capufe.gob.mx/#/ + MX_PASE (91): + Mexico + https://www.pase.com.mx + MX_QUICKPASS (93): + Mexico + https://operadoravial.com/quick-pass/ + MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): + http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf + MX_TAG_IAVE (12): + Mexico + MX_TAG_TELEVIA (13): + Mexico toll pass company. One of many + operating in Mexico City. See additional details + at https://www.televia.com.mx. + MX_TELEVIA (92): + Mexico toll pass company. One of many + operating in Mexico City. + https://www.televia.com.mx + MX_VIAPASS (14): + Mexico toll pass. See additional details at + https://www.viapass.com.mx/viapass/web_home.aspx. + US_AL_FREEDOM_PASS (21): + AL, USA. + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): + AK, USA. + US_CA_FASTRAK (4): + CA, USA. + US_CA_FASTRAK_CAV_STICKER (86): + Indicates driver has any FasTrak pass in + addition to the DMV issued Clean Air Vehicle + (CAV) sticker. + https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml + US_CO_EXPRESSTOLL (23): + CO, USA. + US_CO_GO_PASS (24): + CO, USA. + US_DE_EZPASSDE (25): + DE, USA. + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): + FL, USA. + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): + FL, USA. + US_FL_EPASS (67): + FL, USA. + US_FL_GIBA_TOLL_PASS (68): + FL, USA. + US_FL_LEEWAY (69): + FL, USA. + US_FL_SUNPASS (70): + FL, USA. + US_FL_SUNPASS_PRO (71): + FL, USA. + US_IL_EZPASSIL (73): + IL, USA. + US_IL_IPASS (72): + IL, USA. + US_IN_EZPASSIN (26): + IN, USA. + US_KS_BESTPASS_HORIZON (27): + KS, USA. + US_KS_KTAG (28): + KS, USA. + US_KS_NATIONALPASS (29): + KS, USA. + US_KS_PREPASS_ELITEPASS (30): + KS, USA. + US_KY_RIVERLINK (31): + KY, USA. + US_LA_GEAUXPASS (32): + LA, USA. + US_LA_TOLL_TAG (33): + LA, USA. + US_MA_EZPASSMA (6): + MA, USA. + US_MD_EZPASSMD (34): + MD, USA. + US_ME_EZPASSME (35): + ME, USA. + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): + MI, USA. + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): + MI, USA. + US_MI_IQ_PROX_CARD (38): + MI, USA. + US_MI_MACKINAC_BRIDGE_MAC_PASS (39): + MI, USA. + US_MI_NEXPRESS_TOLL (40): + MI, USA. + US_MN_EZPASSMN (41): + MN, USA. + US_NC_EZPASSNC (42): + NC, USA. + US_NC_PEACH_PASS (87): + NC, USA. + US_NC_QUICK_PASS (43): + NC, USA. + US_NH_EZPASSNH (80): + NH, USA. + US_NJ_DOWNBEACH_EXPRESS_PASS (75): + NJ, USA. + US_NJ_EZPASSNJ (74): + NJ, USA. + US_NY_EXPRESSPASS (76): + NY, USA. + US_NY_EZPASSNY (77): + NY, USA. + US_OH_EZPASSOH (44): + OH, USA. + US_PA_EZPASSPA (45): + PA, USA. + US_RI_EZPASSRI (46): + RI, USA. + US_SC_PALPASS (47): + SC, USA. + US_TX_BANCPASS (48): + TX, USA. + US_TX_DEL_RIO_PASS (49): + TX, USA. + US_TX_EFAST_PASS (50): + TX, USA. + US_TX_EAGLE_PASS_EXPRESS_CARD (51): + TX, USA. + US_TX_EPTOLL (52): + TX, USA. + US_TX_EZ_CROSS (53): + TX, USA. + US_TX_EZTAG (54): + TX, USA. + US_TX_LAREDO_TRADE_TAG (55): + TX, USA. + US_TX_PLUSPASS (56): + TX, USA. + US_TX_TOLLTAG (57): + TX, USA. + US_TX_TXTAG (58): + TX, USA. + US_TX_XPRESS_CARD (59): + TX, USA. + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): + UT, USA. + US_VA_EZPASSVA (61): + VA, USA. + US_WA_BREEZEBY (17): + WA, USA. + US_WA_GOOD_TO_GO (1): + WA, USA. + US_WV_EZPASSWV (62): + WV, USA. + US_WV_MEMORIAL_BRIDGE_TICKETS (63): + WV, USA. + US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): + WV, USA. + """ + TOLL_PASS_UNSPECIFIED = 0 + AU_ETOLL_TAG = 82 + AU_EWAY_TAG = 83 + AU_LINKT = 2 + AR_TELEPASE = 3 + BR_AUTO_EXPRESO = 81 + BR_CONECTCAR = 7 + BR_MOVE_MAIS = 8 + BR_PASSA_RAPIDO = 88 + BR_SEM_PARAR = 9 + BR_TAGGY = 10 + BR_VELOE = 11 + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 + CA_US_BLUE_WATER_EDGE_PASS = 18 + CA_US_CONNEXION = 19 + CA_US_NEXUS_CARD = 20 + ID_E_TOLL = 16 + IN_FASTAG = 78 + IN_LOCAL_HP_PLATE_EXEMPT = 79 + MX_IAVE = 90 + MX_PASE = 91 + MX_QUICKPASS = 93 + MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 + MX_TAG_IAVE = 12 + MX_TAG_TELEVIA = 13 + MX_TELEVIA = 92 + MX_VIAPASS = 14 + US_AL_FREEDOM_PASS = 21 + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 + US_CA_FASTRAK = 4 + US_CA_FASTRAK_CAV_STICKER = 86 + US_CO_EXPRESSTOLL = 23 + US_CO_GO_PASS = 24 + US_DE_EZPASSDE = 25 + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 + US_FL_EPASS = 67 + US_FL_GIBA_TOLL_PASS = 68 + US_FL_LEEWAY = 69 + US_FL_SUNPASS = 70 + US_FL_SUNPASS_PRO = 71 + US_IL_EZPASSIL = 73 + US_IL_IPASS = 72 + US_IN_EZPASSIN = 26 + US_KS_BESTPASS_HORIZON = 27 + US_KS_KTAG = 28 + US_KS_NATIONALPASS = 29 + US_KS_PREPASS_ELITEPASS = 30 + US_KY_RIVERLINK = 31 + US_LA_GEAUXPASS = 32 + US_LA_TOLL_TAG = 33 + US_MA_EZPASSMA = 6 + US_MD_EZPASSMD = 34 + US_ME_EZPASSME = 35 + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 + US_MI_IQ_PROX_CARD = 38 + US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 + US_MI_NEXPRESS_TOLL = 40 + US_MN_EZPASSMN = 41 + US_NC_EZPASSNC = 42 + US_NC_PEACH_PASS = 87 + US_NC_QUICK_PASS = 43 + US_NH_EZPASSNH = 80 + US_NJ_DOWNBEACH_EXPRESS_PASS = 75 + US_NJ_EZPASSNJ = 74 + US_NY_EXPRESSPASS = 76 + US_NY_EZPASSNY = 77 + US_OH_EZPASSOH = 44 + US_PA_EZPASSPA = 45 + US_RI_EZPASSRI = 46 + US_SC_PALPASS = 47 + US_TX_BANCPASS = 48 + US_TX_DEL_RIO_PASS = 49 + US_TX_EFAST_PASS = 50 + US_TX_EAGLE_PASS_EXPRESS_CARD = 51 + US_TX_EPTOLL = 52 + US_TX_EZ_CROSS = 53 + US_TX_EZTAG = 54 + US_TX_LAREDO_TRADE_TAG = 55 + US_TX_PLUSPASS = 56 + US_TX_TOLLTAG = 57 + US_TX_TXTAG = 58 + US_TX_XPRESS_CARD = 59 + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 + US_VA_EZPASSVA = 61 + US_WA_BREEZEBY = 17 + US_WA_GOOD_TO_GO = 1 + US_WV_EZPASSWV = 62 + US_WV_MEMORIAL_BRIDGE_TICKETS = 63 + US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py new file mode 100644 index 000000000000..93cfaf1ee04c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Units', + }, +) + + +class Units(proto.Enum): + r"""A set of values that specify the unit of measure used in the + display. + + Values: + UNITS_UNSPECIFIED (0): + Units of measure not specified. Defaults to + the unit of measure inferred from the request. + METRIC (1): + Metric units of measure. + IMPERIAL (2): + Imperial (English) units of measure. + """ + UNITS_UNSPECIFIED = 0 + METRIC = 1 + IMPERIAL = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py new file mode 100644 index 000000000000..a94a99025c80 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'VehicleEmissionType', + }, +) + + +class VehicleEmissionType(proto.Enum): + r"""A set of values describing the vehicle's emission type. + Applies only to the DRIVE travel mode. + + Values: + VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): + No emission type specified. Default to + GASOLINE. + GASOLINE (1): + Gasoline/petrol fueled vehicle. + ELECTRIC (2): + Electricity powered vehicle. + HYBRID (3): + Hybrid fuel (such as gasoline + electric) + vehicle. + DIESEL (4): + Diesel fueled vehicle. + """ + VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 + GASOLINE = 1 + ELECTRIC = 2 + HYBRID = 3 + DIESEL = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py new file mode 100644 index 000000000000..2d71bb0a70a0 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import vehicle_emission_type + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'VehicleInfo', + }, +) + + +class VehicleInfo(proto.Message): + r"""Encapsulates the vehicle information, such as the license + plate last character. + + Attributes: + emission_type (google.maps.routing_v2.types.VehicleEmissionType): + Describes the vehicle's emission type. + Applies only to the DRIVE travel mode. + """ + + emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( + proto.ENUM, + number=2, + enum=vehicle_emission_type.VehicleEmissionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py new file mode 100644 index 000000000000..c25013cfd086 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import location as gmr_location + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Waypoint', + }, +) + + +class Waypoint(proto.Message): + r"""Encapsulates a waypoint. Waypoints mark both the beginning + and end of a route, and include intermediate stops along the + route. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location (google.maps.routing_v2.types.Location): + A point specified using geographic + coordinates, including an optional heading. + + This field is a member of `oneof`_ ``location_type``. + place_id (str): + The POI Place ID associated with the + waypoint. + + This field is a member of `oneof`_ ``location_type``. + address (str): + Human readable address or a plus code. + See https://plus.codes for details. + + This field is a member of `oneof`_ ``location_type``. + via (bool): + Marks this waypoint as a milestone rather a stopping point. + For each non-via waypoint in the request, the response + appends an entry to the ``legs`` array to provide the + details for stopovers on that leg of the trip. Set this + value to true when you want the route to pass through this + waypoint without stopping over. Via waypoints don't cause an + entry to be added to the ``legs`` array, but they do route + the journey through the waypoint. You can only set this + value on waypoints that are intermediates. The request fails + if you set this field on terminal waypoints. If + ``ComputeRoutesRequest.optimize_waypoint_order`` is set to + true then this field cannot be set to true; otherwise, the + request fails. + vehicle_stopover (bool): + Indicates that the waypoint is meant for vehicles to stop + at, where the intention is to either pickup or drop-off. + When you set this value, the calculated route won't include + non-\ ``via`` waypoints on roads that are unsuitable for + pickup and drop-off. This option works only for ``DRIVE`` + and ``TWO_WHEELER`` travel modes, and when the + ``location_type`` is ``location``. + side_of_road (bool): + Indicates that the location of this waypoint is meant to + have a preference for the vehicle to stop at a particular + side of road. When you set this value, the route will pass + through the location so that the vehicle can stop at the + side of road that the location is biased towards from the + center of the road. This option works only for 'DRIVE' and + 'TWO_WHEELER' travel modes. + """ + + location: gmr_location.Location = proto.Field( + proto.MESSAGE, + number=1, + oneof='location_type', + message=gmr_location.Location, + ) + place_id: str = proto.Field( + proto.STRING, + number=2, + oneof='location_type', + ) + address: str = proto.Field( + proto.STRING, + number=7, + oneof='location_type', + ) + via: bool = proto.Field( + proto.BOOL, + number=3, + ) + vehicle_stopover: bool = proto.Field( + proto.BOOL, + number=4, + ) + side_of_road: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py new file mode 100644 index 000000000000..59757e684c85 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/routing_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py new file mode 100644 index 000000000000..381f53f7a26e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py new file mode 100644 index 000000000000..125691404b0b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py new file mode 100644 index 000000000000..c978c3e55cd7 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py new file mode 100644 index 000000000000..ca13730e4ddc --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json new file mode 100644 index 000000000000..b5ed5aca319c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json @@ -0,0 +1,321 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.routing.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-maps-routing", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_route_matrix_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_route_matrix_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_routes_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py new file mode 100644 index 000000000000..ab8c9f6352a2 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class routingCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'language_code', 'region_code', 'extra_computations', ), + 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'region_code', 'units', 'requested_reference_routes', 'extra_computations', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=routingCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the routing client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py new file mode 100644 index 000000000000..b93d9d947fd8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-maps-routing' + + +description = "Google Maps Routing API client library" + +version = {} +with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "google-geo-type >= 0.1.0, <1.0.0dev", +] +url = "https://github.com/googleapis/python-maps-routing" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.maps"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt new file mode 100644 index 000000000000..33ac865954a6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 +google-geo-type==0.1.0 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py new file mode 100644 index 000000000000..55f7b3a4ba31 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py @@ -0,0 +1,1750 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.maps.routing_v2.services.routes import RoutesAsyncClient +from google.maps.routing_v2.services.routes import RoutesClient +from google.maps.routing_v2.services.routes import transports +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routes_service +from google.maps.routing_v2.types import routing_preference +from google.maps.routing_v2.types import toll_passes +from google.maps.routing_v2.types import units +from google.maps.routing_v2.types import vehicle_emission_type +from google.maps.routing_v2.types import vehicle_info +from google.maps.routing_v2.types import waypoint +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +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 RoutesClient._get_default_mtls_endpoint(None) is None + assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RoutesGrpcTransport, "grpc"), + (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RoutesRestTransport, "rest"), +]) +def test_routes_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +def test_routes_client_get_transport_class(): + transport = RoutesClient.get_transport_class() + available_transports = [ + transports.RoutesGrpcTransport, + transports.RoutesRestTransport, + ] + assert transport in available_transports + + transport = RoutesClient.get_transport_class("grpc") + assert transport == transports.RoutesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +def test_routes_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RoutesClient, transports.RoutesRestTransport, "rest", "true"), + (RoutesClient, transports.RoutesRestTransport, "rest", "false"), +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_routes_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + RoutesClient, RoutesAsyncClient +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +def test_routes_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +def test_routes_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RoutesClient, transports.RoutesRestTransport, "rest", None), +]) +def test_routes_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_routes_client_client_options_from_dict(): + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RoutesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_routes_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "routes.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes(request_type, transport: str = 'grpc'): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = routes_service.ComputeRoutesResponse( + ) + response = client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + client.compute_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + +@pytest.mark.asyncio +async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( + )) + response = await client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +@pytest.mark.asyncio +async def test_compute_routes_async_from_dict(): + await test_compute_routes_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix(request_type, transport: str = 'grpc'): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([routes_service.RouteMatrixElement()]) + response = client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, routes_service.RouteMatrixElement) + + +def test_compute_route_matrix_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + client.compute_route_matrix() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + +@pytest.mark.asyncio +async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) + response = await client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, routes_service.RouteMatrixElement) + + +@pytest.mark.asyncio +async def test_compute_route_matrix_async_from_dict(): + await test_compute_route_matrix_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes_rest(request_type): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = routes_service.ComputeRoutesResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.compute_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): + transport_class = transports.RoutesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.ComputeRoutesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.compute_routes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_routes_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_routes._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_routes_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) + + request = routes_service.ComputeRoutesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.ComputeRoutesResponse() + + client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_routes_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRoutesRequest): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.compute_routes(request) + + +def test_compute_routes_rest_error(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix_rest(request_type): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = routes_service.RouteMatrixElement( + origin_index=1279, + destination_index=1817, + condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, + distance_meters=1594, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.compute_route_matrix(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.RouteMatrixElement) + assert response.origin_index == 1279 + assert response.destination_index == 1817 + assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS + assert response.distance_meters == 1594 + + +def test_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): + transport_class = transports.RoutesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.RouteMatrixElement() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.compute_route_matrix(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_route_matrix_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_route_matrix_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) + req.return_value._content = "[{}]".format(req.return_value._content) + + request = routes_service.ComputeRouteMatrixRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.RouteMatrixElement() + + client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_route_matrix_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.compute_route_matrix(request) + + +def test_compute_route_matrix_rest_error(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutesClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RoutesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RoutesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = RoutesClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RoutesGrpcTransport, + ) + +def test_routes_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_routes_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'compute_routes', + 'compute_route_matrix', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_routes_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +def test_routes_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport() + adc.assert_called_once() + + +def test_routes_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RoutesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + ], +) +def test_routes_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, + ], +) +def test_routes_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RoutesGrpcTransport, grpc_helpers), + (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_routes_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "routes.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_routes_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.RoutesRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_routes_host_no_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_routes_host_with_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_routes_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RoutesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RoutesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.compute_routes._session + session2 = client2.transport.compute_routes._session + assert session1 != session2 + session1 = client1.transport.compute_route_matrix._session + session2 = client2.transport.compute_route_matrix._session + assert session1 != session2 +def test_routes_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_routes_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + 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 + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + 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=cred, + credentials_file=None, + scopes=None, + 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 + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_transport_channel_mtls_with_adc( + transport_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), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + 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 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RoutesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RoutesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = RoutesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RoutesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RoutesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RoutesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = RoutesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RoutesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RoutesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RoutesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: + transport_class = RoutesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (RoutesClient, transports.RoutesGrpcTransport), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From 9c46ac0a7603075713d779e135e28d353720b591 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 17 Mar 2023 22:51:05 +0000 Subject: [PATCH 08/12] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../google-maps-routing/v2/.coveragerc | 13 - .../google-maps-routing/v2/.flake8 | 33 - .../google-maps-routing/v2/MANIFEST.in | 2 - .../google-maps-routing/v2/README.rst | 49 - .../google-maps-routing/v2/docs/conf.py | 376 ---- .../google-maps-routing/v2/docs/index.rst | 7 - .../v2/docs/routing_v2/routes.rst | 6 - .../v2/docs/routing_v2/services.rst | 6 - .../v2/docs/routing_v2/types.rst | 6 - .../v2/google/maps/routing/__init__.py | 97 - .../v2/google/maps/routing/gapic_version.py | 16 - .../v2/google/maps/routing/py.typed | 2 - .../v2/google/maps/routing_v2/__init__.py | 98 - .../maps/routing_v2/gapic_metadata.json | 58 - .../google/maps/routing_v2/gapic_version.py | 16 - .../v2/google/maps/routing_v2/py.typed | 2 - .../maps/routing_v2/services/__init__.py | 15 - .../routing_v2/services/routes/__init__.py | 22 - .../services/routes/async_client.py | 416 ---- .../maps/routing_v2/services/routes/client.py | 613 ------ .../services/routes/transports/__init__.py | 38 - .../services/routes/transports/base.py | 161 -- .../services/routes/transports/grpc.py | 363 ---- .../routes/transports/grpc_asyncio.py | 362 ---- .../services/routes/transports/rest.py | 417 ---- .../google/maps/routing_v2/types/__init__.py | 105 - .../maps/routing_v2/types/fallback_info.py | 103 - .../routing_v2/types/geocoding_results.py | 125 -- .../google/maps/routing_v2/types/location.py | 62 - .../google/maps/routing_v2/types/maneuver.py | 96 - .../types/navigation_instruction.py | 58 - .../google/maps/routing_v2/types/polyline.py | 113 -- .../v2/google/maps/routing_v2/types/route.py | 409 ---- .../maps/routing_v2/types/route_label.py | 57 - .../maps/routing_v2/types/route_modifiers.py | 97 - .../routing_v2/types/route_travel_mode.py | 59 - .../maps/routing_v2/types/routes_service.py | 541 ----- .../routing_v2/types/routing_preference.py | 67 - .../types/speed_reading_interval.py | 89 - .../google/maps/routing_v2/types/toll_info.py | 56 - .../maps/routing_v2/types/toll_passes.py | 348 ---- .../v2/google/maps/routing_v2/types/units.py | 49 - .../routing_v2/types/vehicle_emission_type.py | 56 - .../maps/routing_v2/types/vehicle_info.py | 50 - .../google/maps/routing_v2/types/waypoint.py | 123 -- .../google-maps-routing/v2/mypy.ini | 3 - .../google-maps-routing/v2/noxfile.py | 184 -- ...rated_routes_compute_route_matrix_async.py | 52 - ...erated_routes_compute_route_matrix_sync.py | 52 - ...2_generated_routes_compute_routes_async.py | 51 - ...v2_generated_routes_compute_routes_sync.py | 51 - ...ippet_metadata_google.maps.routing.v2.json | 321 --- .../v2/scripts/fixup_routing_v2_keywords.py | 177 -- .../google-maps-routing/v2/setup.py | 91 - .../v2/testing/constraints-3.10.txt | 7 - .../v2/testing/constraints-3.11.txt | 7 - .../v2/testing/constraints-3.12.txt | 7 - .../v2/testing/constraints-3.7.txt | 10 - .../v2/testing/constraints-3.8.txt | 7 - .../v2/testing/constraints-3.9.txt | 7 - .../google-maps-routing/v2/tests/__init__.py | 16 - .../v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/routing_v2/__init__.py | 16 - .../unit/gapic/routing_v2/test_routes.py | 1750 ----------------- .../maps/routing_v2/types/routes_service.py | 29 + .../scripts/fixup_routing_v2_keywords.py | 4 +- 67 files changed, 31 insertions(+), 8700 deletions(-) delete mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc delete mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 delete mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini delete mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py diff --git a/owl-bot-staging/google-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc deleted file mode 100644 index d0ce5597b0a9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/routing/__init__.py - google/maps/routing/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.flake8 +++ /dev/null @@ -1,33 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in deleted file mode 100644 index c5b56c111c00..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/routing *.py -recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst deleted file mode 100644 index f0002366e552..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Routing API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Maps Routing API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py deleted file mode 100644 index d7a10abed96b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-maps-routing documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -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"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-maps-routing" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# 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"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# 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 - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -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 = { - "description": "Google Maps Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# 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 - -# 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 - -# 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, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# 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 = [] - -# 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' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is 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 = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# 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' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# 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' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-maps-routing-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- 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', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-maps-routing.tex", - u"google-maps-routing 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 - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# 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 = [ - ( - root_doc, - "google-maps-routing", - u"Google Maps Routing Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-maps-routing", - u"google-maps-routing Documentation", - author, - "google-maps-routing", - "GAPIC library for Google Maps Routing API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# 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), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst deleted file mode 100644 index e2563dd88ee9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - routing_v2/services - routing_v2/types diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst deleted file mode 100644 index 3d52309cddae..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst +++ /dev/null @@ -1,6 +0,0 @@ -Routes ------------------------- - -.. automodule:: google.maps.routing_v2.services.routes - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst deleted file mode 100644 index e96568dc434c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Routing v2 API -======================================= -.. toctree:: - :maxdepth: 2 - - routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst deleted file mode 100644 index 176a5a812cf8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Routing v2 API -==================================== - -.. automodule:: google.maps.routing_v2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py deleted file mode 100644 index 59020a3484c3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.maps.routing import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.routing_v2.services.routes.client import RoutesClient -from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient - -from google.maps.routing_v2.types.fallback_info import FallbackInfo -from google.maps.routing_v2.types.fallback_info import FallbackReason -from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode -from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint -from google.maps.routing_v2.types.geocoding_results import GeocodingResults -from google.maps.routing_v2.types.location import Location -from google.maps.routing_v2.types.maneuver import Maneuver -from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction -from google.maps.routing_v2.types.polyline import Polyline -from google.maps.routing_v2.types.polyline import PolylineEncoding -from google.maps.routing_v2.types.polyline import PolylineQuality -from google.maps.routing_v2.types.route import Route -from google.maps.routing_v2.types.route import RouteLeg -from google.maps.routing_v2.types.route import RouteLegStep -from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory -from google.maps.routing_v2.types.route import RouteLegTravelAdvisory -from google.maps.routing_v2.types.route import RouteTravelAdvisory -from google.maps.routing_v2.types.route_label import RouteLabel -from google.maps.routing_v2.types.route_modifiers import RouteModifiers -from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode -from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse -from google.maps.routing_v2.types.routes_service import RouteMatrixDestination -from google.maps.routing_v2.types.routes_service import RouteMatrixElement -from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin -from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition -from google.maps.routing_v2.types.routing_preference import RoutingPreference -from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval -from google.maps.routing_v2.types.toll_info import TollInfo -from google.maps.routing_v2.types.toll_passes import TollPass -from google.maps.routing_v2.types.units import Units -from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType -from google.maps.routing_v2.types.vehicle_info import VehicleInfo -from google.maps.routing_v2.types.waypoint import Waypoint - -__all__ = ('RoutesClient', - 'RoutesAsyncClient', - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py deleted file mode 100644 index 405b1cebcf15..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py deleted file mode 100644 index cd9d694f63c6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.maps.routing_v2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.routes import RoutesClient -from .services.routes import RoutesAsyncClient - -from .types.fallback_info import FallbackInfo -from .types.fallback_info import FallbackReason -from .types.fallback_info import FallbackRoutingMode -from .types.geocoding_results import GeocodedWaypoint -from .types.geocoding_results import GeocodingResults -from .types.location import Location -from .types.maneuver import Maneuver -from .types.navigation_instruction import NavigationInstruction -from .types.polyline import Polyline -from .types.polyline import PolylineEncoding -from .types.polyline import PolylineQuality -from .types.route import Route -from .types.route import RouteLeg -from .types.route import RouteLegStep -from .types.route import RouteLegStepTravelAdvisory -from .types.route import RouteLegTravelAdvisory -from .types.route import RouteTravelAdvisory -from .types.route_label import RouteLabel -from .types.route_modifiers import RouteModifiers -from .types.route_travel_mode import RouteTravelMode -from .types.routes_service import ComputeRouteMatrixRequest -from .types.routes_service import ComputeRoutesRequest -from .types.routes_service import ComputeRoutesResponse -from .types.routes_service import RouteMatrixDestination -from .types.routes_service import RouteMatrixElement -from .types.routes_service import RouteMatrixOrigin -from .types.routes_service import RouteMatrixElementCondition -from .types.routing_preference import RoutingPreference -from .types.speed_reading_interval import SpeedReadingInterval -from .types.toll_info import TollInfo -from .types.toll_passes import TollPass -from .types.units import Units -from .types.vehicle_emission_type import VehicleEmissionType -from .types.vehicle_info import VehicleInfo -from .types.waypoint import Waypoint - -__all__ = ( - 'RoutesAsyncClient', -'ComputeRouteMatrixRequest', -'ComputeRoutesRequest', -'ComputeRoutesResponse', -'FallbackInfo', -'FallbackReason', -'FallbackRoutingMode', -'GeocodedWaypoint', -'GeocodingResults', -'Location', -'Maneuver', -'NavigationInstruction', -'Polyline', -'PolylineEncoding', -'PolylineQuality', -'Route', -'RouteLabel', -'RouteLeg', -'RouteLegStep', -'RouteLegStepTravelAdvisory', -'RouteLegTravelAdvisory', -'RouteMatrixDestination', -'RouteMatrixElement', -'RouteMatrixElementCondition', -'RouteMatrixOrigin', -'RouteModifiers', -'RouteTravelAdvisory', -'RouteTravelMode', -'RoutesClient', -'RoutingPreference', -'SpeedReadingInterval', -'TollInfo', -'TollPass', -'Units', -'VehicleEmissionType', -'VehicleInfo', -'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json deleted file mode 100644 index 8382cea1d39a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json +++ /dev/null @@ -1,58 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.routing_v2", - "protoPackage": "google.maps.routing.v2", - "schema": "1.0", - "services": { - "Routes": { - "clients": { - "grpc": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RoutesAsyncClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "rest": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py deleted file mode 100644 index 405b1cebcf15..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py deleted file mode 100644 index e8e1c3845db5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py deleted file mode 100644 index ff3f8f71863f..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import RoutesClient -from .async_client import RoutesAsyncClient - -__all__ = ( - 'RoutesClient', - 'RoutesAsyncClient', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py deleted file mode 100644 index 7f8df74a140b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union - -from google.maps.routing_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .client import RoutesClient - - -class RoutesAsyncClient: - """The Routes API.""" - - _client: RoutesClient - - DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RoutesClient.common_folder_path) - parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) - common_organization_path = staticmethod(RoutesClient.common_organization_path) - parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) - common_project_path = staticmethod(RoutesClient.common_project_path) - parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) - common_location_path = staticmethod(RoutesClient.common_location_path) - parse_common_location_path = staticmethod(RoutesClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(RoutesClient).get_transport_class, type(RoutesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, RoutesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.RoutesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RoutesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # Create or coerce a protobuf request object. - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.compute_routes, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - # Create or coerce a protobuf request object. - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.compute_route_matrix, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RoutesAsyncClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py deleted file mode 100644 index 1943383c7246..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py +++ /dev/null @@ -1,613 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast - -from google.maps.routing_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RoutesGrpcTransport -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .transports.rest import RoutesRestTransport - - -class RoutesClientMeta(type): - """Metaclass for the Routes client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] - _transport_registry["grpc"] = RoutesGrpcTransport - _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport - _transport_registry["rest"] = RoutesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RoutesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class RoutesClient(metaclass=RoutesClientMeta): - """The Routes API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "routes.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RoutesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, RoutesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, RoutesTransport): - # transport is a RoutesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a routes_service.ComputeRoutesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, routes_service.ComputeRoutesRequest): - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_routes] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[routes_service.RouteMatrixElement]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - Iterable[google.maps.routing_v2.types.RouteMatrixElement]: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a routes_service.ComputeRouteMatrixRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, routes_service.ComputeRouteMatrixRequest): - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "RoutesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RoutesClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py deleted file mode 100644 index a15967f001c9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import RoutesTransport -from .grpc import RoutesGrpcTransport -from .grpc_asyncio import RoutesGrpcAsyncIOTransport -from .rest import RoutesRestTransport -from .rest import RoutesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] -_transport_registry['grpc'] = RoutesGrpcTransport -_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport -_transport_registry['rest'] = RoutesRestTransport - -__all__ = ( - 'RoutesTransport', - 'RoutesGrpcTransport', - 'RoutesGrpcAsyncIOTransport', - 'RoutesRestTransport', - 'RoutesRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py deleted file mode 100644 index a6fa68993eca..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py +++ /dev/null @@ -1,161 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.maps.routing_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.maps.routing_v2.types import routes_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class RoutesTransport(abc.ABC): - """Abstract transport class for Routes.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'routes.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.compute_routes: gapic_v1.method.wrap_method( - self.compute_routes, - default_timeout=None, - client_info=client_info, - ), - self.compute_route_matrix: gapic_v1.method.wrap_method( - self.compute_route_matrix, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Union[ - routes_service.ComputeRoutesResponse, - Awaitable[routes_service.ComputeRoutesResponse] - ]]: - raise NotImplementedError() - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Union[ - routes_service.RouteMatrixElement, - Awaitable[routes_service.RouteMatrixElement] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RoutesTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py deleted file mode 100644 index 8316c8b03587..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py +++ /dev/null @@ -1,363 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO - - -class RoutesGrpcTransport(RoutesTransport): - """gRPC backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - ~.ComputeRoutesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self.grpc_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - ~.RouteMatrixElement]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RoutesGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py deleted file mode 100644 index 752c5eaefc33..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py +++ /dev/null @@ -1,362 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO -from .grpc import RoutesGrpcTransport - - -class RoutesGrpcAsyncIOTransport(RoutesTransport): - """gRPC AsyncIO backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Awaitable[routes_service.ComputeRoutesResponse]]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - Awaitable[~.ComputeRoutesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self.grpc_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Awaitable[routes_service.RouteMatrixElement]]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - Awaitable[~.RouteMatrixElement]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'RoutesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py deleted file mode 100644 index c7fdf524b0c7..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.maps.routing_v2.types import routes_service - -from .base import RoutesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class RoutesRestInterceptor: - """Interceptor for Routes. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the RoutesRestTransport. - - .. code-block:: python - class MyCustomRoutesInterceptor(RoutesRestInterceptor): - def pre_compute_route_matrix(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_route_matrix(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_compute_routes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_routes(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) - client = RoutesClient(transport=transport) - - - """ - def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: - """Post-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compute_routes - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: - """Post-rpc interceptor for compute_routes - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class RoutesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RoutesRestInterceptor - - -class RoutesRestTransport(RoutesTransport): - """REST backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[RoutesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or RoutesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ComputeRouteMatrix(RoutesRestStub): - def __hash__(self): - return hash("ComputeRouteMatrix") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: routes_service.ComputeRouteMatrixRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> rest_streaming.ResponseIterator: - r"""Call the compute route matrix method over HTTP. - - Args: - request (~.routes_service.ComputeRouteMatrixRequest): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.routes_service.RouteMatrixElement: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/distanceMatrix/v2:computeRouteMatrix', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) - pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) - resp = self._interceptor.post_compute_route_matrix(resp) - return resp - - class _ComputeRoutes(RoutesRestStub): - def __hash__(self): - return hash("ComputeRoutes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: routes_service.ComputeRoutesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> routes_service.ComputeRoutesResponse: - r"""Call the compute routes method over HTTP. - - Args: - request (~.routes_service.ComputeRoutesRequest): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.routes_service.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/directions/v2:computeRoutes', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_compute_routes(request, metadata) - pb_request = routes_service.ComputeRoutesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = routes_service.ComputeRoutesResponse() - pb_resp = routes_service.ComputeRoutesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_compute_routes(resp) - return resp - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RoutesRestTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py deleted file mode 100644 index 7323899cfc30..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .fallback_info import ( - FallbackInfo, - FallbackReason, - FallbackRoutingMode, -) -from .geocoding_results import ( - GeocodedWaypoint, - GeocodingResults, -) -from .location import ( - Location, -) -from .navigation_instruction import ( - NavigationInstruction, -) -from .polyline import ( - Polyline, - PolylineEncoding, - PolylineQuality, -) -from .route import ( - Route, - RouteLeg, - RouteLegStep, - RouteLegStepTravelAdvisory, - RouteLegTravelAdvisory, - RouteTravelAdvisory, -) -from .route_modifiers import ( - RouteModifiers, -) -from .routes_service import ( - ComputeRouteMatrixRequest, - ComputeRoutesRequest, - ComputeRoutesResponse, - RouteMatrixDestination, - RouteMatrixElement, - RouteMatrixOrigin, - RouteMatrixElementCondition, -) -from .speed_reading_interval import ( - SpeedReadingInterval, -) -from .toll_info import ( - TollInfo, -) -from .vehicle_info import ( - VehicleInfo, -) -from .waypoint import ( - Waypoint, -) - -__all__ = ( - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py deleted file mode 100644 index 99670aafac25..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'FallbackReason', - 'FallbackRoutingMode', - 'FallbackInfo', - }, -) - - -class FallbackReason(proto.Enum): - r"""Reasons for using fallback response. - - Values: - FALLBACK_REASON_UNSPECIFIED (0): - No fallback reason specified. - SERVER_ERROR (1): - A server error happened while calculating - routes with your preferred routing mode, but we - were able to return a result calculated by an - alternative mode. - LATENCY_EXCEEDED (2): - We were not able to finish the calculation - with your preferred routing mode on time, but we - were able to return a result calculated by an - alternative mode. - """ - FALLBACK_REASON_UNSPECIFIED = 0 - SERVER_ERROR = 1 - LATENCY_EXCEEDED = 2 - - -class FallbackRoutingMode(proto.Enum): - r"""Actual routing mode used for returned fallback response. - - Values: - FALLBACK_ROUTING_MODE_UNSPECIFIED (0): - Not used. - FALLBACK_TRAFFIC_UNAWARE (1): - Indicates the "TRAFFIC_UNAWARE" routing mode was used to - compute the response. - FALLBACK_TRAFFIC_AWARE (2): - Indicates the "TRAFFIC_AWARE" routing mode was used to - compute the response. - """ - FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 - FALLBACK_TRAFFIC_UNAWARE = 1 - FALLBACK_TRAFFIC_AWARE = 2 - - -class FallbackInfo(proto.Message): - r"""Information related to how and why a fallback result was - used. If this field is set, then it means the server used a - different routing mode from your preferred mode as fallback. - - Attributes: - routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): - Routing mode used for the response. If - fallback was triggered, the mode may be - different from routing preference set in the - original client request. - reason (google.maps.routing_v2.types.FallbackReason): - The reason why fallback response was used - instead of the original response. This field is - only populated when the fallback mode is - triggered and the fallback response is returned. - """ - - routing_mode: 'FallbackRoutingMode' = proto.Field( - proto.ENUM, - number=1, - enum='FallbackRoutingMode', - ) - reason: 'FallbackReason' = proto.Field( - proto.ENUM, - number=2, - enum='FallbackReason', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py deleted file mode 100644 index ffa385a59a75..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py +++ /dev/null @@ -1,125 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'GeocodingResults', - 'GeocodedWaypoint', - }, -) - - -class GeocodingResults(proto.Message): - r"""Contains GeocodedWaypoints for origin, destination and - intermediate waypoints. Only populated for address waypoints. - - Attributes: - origin (google.maps.routing_v2.types.GeocodedWaypoint): - Origin geocoded waypoint. - destination (google.maps.routing_v2.types.GeocodedWaypoint): - Destination geocoded waypoint. - intermediates (MutableSequence[google.maps.routing_v2.types.GeocodedWaypoint]): - A list of intermediate geocoded waypoints - each containing an index field that corresponds - to the zero-based position of the waypoint in - the order they were specified in the request. - """ - - origin: 'GeocodedWaypoint' = proto.Field( - proto.MESSAGE, - number=1, - message='GeocodedWaypoint', - ) - destination: 'GeocodedWaypoint' = proto.Field( - proto.MESSAGE, - number=2, - message='GeocodedWaypoint', - ) - intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='GeocodedWaypoint', - ) - - -class GeocodedWaypoint(proto.Message): - r"""Details about the locations used as waypoints. Only populated - for address waypoints. Includes details about the geocoding - results for the purposes of determining what the address was - geocoded to. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - geocoder_status (google.rpc.status_pb2.Status): - Indicates the status code resulting from the - geocoding operation. - intermediate_waypoint_request_index (int): - The index of the corresponding intermediate - waypoint in the request. Only populated if the - corresponding waypoint is an intermediate - waypoint. - - This field is a member of `oneof`_ ``_intermediate_waypoint_request_index``. - type_ (MutableSequence[str]): - The type(s) of the result, in the form of - zero or more type tags. Supported types: - https://developers.google.com/maps/documentation/geocoding/requests-geocoding#Types - partial_match (bool): - Indicates that the geocoder did not return an - exact match for the original request, though it - was able to match part of the requested address. - You may wish to examine the original request for - misspellings and/or an incomplete address. - place_id (str): - The place ID for this result. - """ - - geocoder_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - intermediate_waypoint_request_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - type_: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - partial_match: bool = proto.Field( - proto.BOOL, - number=4, - ) - place_id: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py deleted file mode 100644 index 722cd7dda46a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Location', - }, -) - - -class Location(proto.Message): - r"""Encapsulates a location (a geographic point, and an optional - heading). - - Attributes: - lat_lng (google.type.latlng_pb2.LatLng): - The waypoint's geographic coordinates. - heading (google.protobuf.wrappers_pb2.Int32Value): - The compass heading associated with the direction of the - flow of traffic. This value is used to specify the side of - the road to use for pickup and drop-off. Heading values can - be from 0 to 360, where 0 specifies a heading of due North, - 90 specifies a heading of due East, etc. You can use this - field only for ``DRIVE`` and ``TWO_WHEELER`` travel modes. - """ - - lat_lng: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - heading: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py deleted file mode 100644 index 60e5cd3cb9c6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Maneuver', - }, -) - - -class Maneuver(proto.Enum): - r"""A set of values that specify the navigation action to take - for the current step (e.g., turn left, merge, straight, etc.). - - Values: - MANEUVER_UNSPECIFIED (0): - Not used. - TURN_SLIGHT_LEFT (1): - Turn slightly to the left. - TURN_SHARP_LEFT (2): - Turn sharply to the left. - UTURN_LEFT (3): - Make a left u-turn. - TURN_LEFT (4): - Turn left. - TURN_SLIGHT_RIGHT (5): - Turn slightly to the right. - TURN_SHARP_RIGHT (6): - Turn sharply to the right. - UTURN_RIGHT (7): - Make a right u-turn. - TURN_RIGHT (8): - Turn right. - STRAIGHT (9): - Go straight. - RAMP_LEFT (10): - Take the left ramp. - RAMP_RIGHT (11): - Take the right ramp. - MERGE (12): - Merge into traffic. - FORK_LEFT (13): - Take the left fork. - FORK_RIGHT (14): - Take the right fork. - FERRY (15): - Take the ferry. - FERRY_TRAIN (16): - Take the train leading onto the ferry. - ROUNDABOUT_LEFT (17): - Turn left at the roundabout. - ROUNDABOUT_RIGHT (18): - Turn right at the roundabout. - """ - MANEUVER_UNSPECIFIED = 0 - TURN_SLIGHT_LEFT = 1 - TURN_SHARP_LEFT = 2 - UTURN_LEFT = 3 - TURN_LEFT = 4 - TURN_SLIGHT_RIGHT = 5 - TURN_SHARP_RIGHT = 6 - UTURN_RIGHT = 7 - TURN_RIGHT = 8 - STRAIGHT = 9 - RAMP_LEFT = 10 - RAMP_RIGHT = 11 - MERGE = 12 - FORK_LEFT = 13 - FORK_RIGHT = 14 - FERRY = 15 - FERRY_TRAIN = 16 - ROUNDABOUT_LEFT = 17 - ROUNDABOUT_RIGHT = 18 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py deleted file mode 100644 index dc8b69e76ccd..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import maneuver as gmr_maneuver - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'NavigationInstruction', - }, -) - - -class NavigationInstruction(proto.Message): - r"""Encapsulates navigation instructions for a - [RouteLegStep][google.maps.routing.v2.RouteLegStep] - - Attributes: - maneuver (google.maps.routing_v2.types.Maneuver): - Encapsulates the navigation instructions for - the current step (e.g., turn left, merge, - straight, etc.). This field determines which - icon to display. - instructions (str): - Instructions for navigating this step. - """ - - maneuver: gmr_maneuver.Maneuver = proto.Field( - proto.ENUM, - number=1, - enum=gmr_maneuver.Maneuver, - ) - instructions: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py deleted file mode 100644 index 4d9630691288..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'PolylineQuality', - 'PolylineEncoding', - 'Polyline', - }, -) - - -class PolylineQuality(proto.Enum): - r"""A set of values that specify the quality of the polyline. - - Values: - POLYLINE_QUALITY_UNSPECIFIED (0): - No polyline quality preference specified. Defaults to - ``OVERVIEW``. - HIGH_QUALITY (1): - Specifies a high-quality polyline - which is composed using - more points than ``OVERVIEW``, at the cost of increased - response size. Use this value when you need more precision. - OVERVIEW (2): - Specifies an overview polyline - which is composed using a - small number of points. Use this value when displaying an - overview of the route. Using this option has a lower request - latency compared to using the ``HIGH_QUALITY`` option. - """ - POLYLINE_QUALITY_UNSPECIFIED = 0 - HIGH_QUALITY = 1 - OVERVIEW = 2 - - -class PolylineEncoding(proto.Enum): - r"""Specifies the preferred type of polyline to be returned. - - Values: - POLYLINE_ENCODING_UNSPECIFIED (0): - No polyline type preference specified. Defaults to - ``ENCODED_POLYLINE``. - ENCODED_POLYLINE (1): - Specifies a polyline encoded using the `polyline encoding - algorithm `__. - GEO_JSON_LINESTRING (2): - Specifies a polyline using the `GeoJSON LineString - format `__ - """ - POLYLINE_ENCODING_UNSPECIFIED = 0 - ENCODED_POLYLINE = 1 - GEO_JSON_LINESTRING = 2 - - -class Polyline(proto.Message): - r"""Encapsulates an encoded polyline. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - encoded_polyline (str): - The string encoding of the polyline using the `polyline - encoding - algorithm `__ - - This field is a member of `oneof`_ ``polyline_type``. - geo_json_linestring (google.protobuf.struct_pb2.Struct): - Specifies a polyline using the `GeoJSON LineString - format `__ - - This field is a member of `oneof`_ ``polyline_type``. - """ - - encoded_polyline: str = proto.Field( - proto.STRING, - number=1, - oneof='polyline_type', - ) - geo_json_linestring: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - oneof='polyline_type', - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py deleted file mode 100644 index 2a57054febff..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py +++ /dev/null @@ -1,409 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.geo.type import viewport_pb2 # type: ignore -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction -from google.maps.routing_v2.types import polyline as gmr_polyline -from google.maps.routing_v2.types import route_label -from google.maps.routing_v2.types import speed_reading_interval -from google.maps.routing_v2.types import toll_info as gmr_toll_info -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Route', - 'RouteTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteLegStepTravelAdvisory', - 'RouteLeg', - 'RouteLegStep', - }, -) - - -class Route(proto.Message): - r"""Encapsulates a route, which consists of a series of connected - road segments that join beginning, ending, and intermediate - waypoints. - - Attributes: - route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): - Labels for the ``Route`` that are useful to identify - specific properties of the route to compare against others. - legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): - A collection of legs (path segments between waypoints) that - make-up the route. Each leg corresponds to the trip between - two non-\ ``via`` Waypoints. For example, a route with no - intermediate waypoints has only one leg. A route that - includes one non-\ ``via`` intermediate waypoint has two - legs. A route that includes one ``via`` intermediate - waypoint has one leg. The order of the legs matches the - order of Waypoints from ``origin`` to ``intermediates`` to - ``destination``. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the route - without taking traffic conditions into - consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall route polyline. This polyline will be the - combined polyline of all ``legs``. - description (str): - A description of the route. - warnings (MutableSequence[str]): - An array of warnings to show when displaying - the route. - viewport (google.geo.type.viewport_pb2.Viewport): - The viewport bounding box of the polyline. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. - route_token (str): - Web-safe base64 encoded route token that can be passed to - NavigationSDK, which allows the Navigation SDK to - reconstruct the route during navigation, and in the event of - rerouting honor the original intention when Routes - ComputeRoutes is called. Customers should treat this token - as an opaque blob. NOTE: ``Route.route_token`` is only - available for requests that have set - ``ComputeRoutesRequest.routing_preference`` to - ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. - ``Route.route_token`` is also not supported for requests - that have Via waypoints. - """ - - route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( - proto.ENUM, - number=13, - enum=route_label.RouteLabel, - ) - legs: MutableSequence['RouteLeg'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteLeg', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=2, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_polyline.Polyline, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - warnings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - viewport: viewport_pb2.Viewport = proto.Field( - proto.MESSAGE, - number=8, - message=viewport_pb2.Viewport, - ) - travel_advisory: 'RouteTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=9, - message='RouteTravelAdvisory', - ) - route_token: str = proto.Field( - proto.STRING, - number=12, - ) - - -class RouteTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction - etc. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Encapsulates information about tolls on the Route. This - field is only populated if we expect there are tolls on the - Route. If this field is set but the estimated_price subfield - is not populated, we expect that road contains tolls but we - do not know an estimated price. If this field is not set, - then we expect there is no toll on the Route. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the route without overlap. The - start point of a specified interval is the same as the end - point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - fuel_consumption_microliters (int): - The fuel consumption prediction in - microliters. - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=speed_reading_interval.SpeedReadingInterval, - ) - fuel_consumption_microliters: int = proto.Field( - proto.INT64, - number=5, - ) - - -class RouteLegTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction - etc. on a route leg. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Encapsulates information about tolls on the specific - RouteLeg. This field is only populated if we expect there - are tolls on the RouteLeg. If this field is set but the - estimated_price subfield is not populated, we expect that - road contains tolls but we do not know an estimated price. - If this field does not exist, then there is no toll on the - RouteLeg. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the RouteLg without overlap. - The start point of a specified interval is the same as the - end point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLegStepTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction on - a leg step. - - Attributes: - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - NOTE: This field is not currently populated. - """ - - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLeg(proto.Message): - r"""Encapsulates a segment between non-\ ``via`` waypoints. - - Attributes: - distance_meters (int): - The travel distance of the route leg, in - meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the leg. If the - ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then - this value is the same as ``static_duration``. If the - ``route_preference`` is either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the leg, - calculated without taking traffic conditions - into consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall polyline for this leg. This includes that each - ``step``'s polyline. - start_location (google.maps.routing_v2.types.Location): - The start location of this leg. This might be different from - the provided ``origin``. For example, when the provided - ``origin`` is not near a road, this is a point on the road. - end_location (google.maps.routing_v2.types.Location): - The end location of this leg. This might be different from - the provided ``destination``. For example, when the provided - ``destination`` is not near a road, this is a point on the - road. - steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): - An array of steps denoting segments within - this leg. Each step represents one navigation - instruction. - travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): - Encapsulates the additional information that - the user should be informed about, such as - possible traffic zone restriction etc. on a - route leg. - """ - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=4, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=6, - message=location.Location, - ) - steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='RouteLegStep', - ) - travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=8, - message='RouteLegTravelAdvisory', - ) - - -class RouteLegStep(proto.Message): - r"""Encapsulates a segment of a ``RouteLeg``. A step corresponds to a - single navigation instruction. Route legs are made up of steps. - - Attributes: - distance_meters (int): - The travel distance of this step, in meters. - In some circumstances, this field might not have - a value. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of travel through this step - without taking traffic conditions into - consideration. In some circumstances, this field - might not have a value. - polyline (google.maps.routing_v2.types.Polyline): - The polyline associated with this step. - start_location (google.maps.routing_v2.types.Location): - The start location of this step. - end_location (google.maps.routing_v2.types.Location): - The end location of this step. - navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): - Navigation instructions. - travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): - Encapsulates the additional information that - the user should be informed about, such as - possible traffic zone restriction on a leg step. - """ - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=4, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( - proto.MESSAGE, - number=6, - message=gmr_navigation_instruction.NavigationInstruction, - ) - travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=7, - message='RouteLegStepTravelAdvisory', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py deleted file mode 100644 index a3e095209d58..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteLabel', - }, -) - - -class RouteLabel(proto.Enum): - r"""Labels for the ``Route`` that are useful to identify specific - properties of the route to compare against others. - - Values: - ROUTE_LABEL_UNSPECIFIED (0): - Default - not used. - DEFAULT_ROUTE (1): - The default "best" route returned for the - route computation. - DEFAULT_ROUTE_ALTERNATE (2): - An alternative to the default "best" route. Routes like this - will be returned when - ``ComputeRoutesRequest.compute_alternative_routes`` is - specified. - FUEL_EFFICIENT (3): - Fuel efficient route. Routes labeled with - this value are determined to be optimized for - Eco parameters such as fuel consumption. - """ - ROUTE_LABEL_UNSPECIFIED = 0 - DEFAULT_ROUTE = 1 - DEFAULT_ROUTE_ALTERNATE = 2 - FUEL_EFFICIENT = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py deleted file mode 100644 index 59f5e6420c4c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import toll_passes as gmr_toll_passes -from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteModifiers', - }, -) - - -class RouteModifiers(proto.Message): - r"""Encapsulates a set of optional conditions to satisfy when - calculating the routes. - - Attributes: - avoid_tolls (bool): - Specifies whether to avoid toll roads where reasonable. - Preference will be given to routes not containing toll - roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - travel modes. - avoid_highways (bool): - Specifies whether to avoid highways where reasonable. - Preference will be given to routes not containing highways. - Applies only to the ``DRIVE`` and ``TWO_WHEELER`` travel - modes. - avoid_ferries (bool): - Specifies whether to avoid ferries where reasonable. - Preference will be given to routes not containing travel by - ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` - travel modes. - avoid_indoor (bool): - Specifies whether to avoid navigating indoors where - reasonable. Preference will be given to routes not - containing indoor navigation. Applies only to the ``WALK`` - travel mode. - vehicle_info (google.maps.routing_v2.types.VehicleInfo): - Specifies the vehicle information. - toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): - Encapsulates information about toll passes. If toll passes - are provided, the API tries to return the pass price. If - toll passes are not provided, the API treats the toll pass - as unknown and tries to return the cash price. Applies only - to the DRIVE and TWO_WHEELER travel modes. - """ - - avoid_tolls: bool = proto.Field( - proto.BOOL, - number=1, - ) - avoid_highways: bool = proto.Field( - proto.BOOL, - number=2, - ) - avoid_ferries: bool = proto.Field( - proto.BOOL, - number=3, - ) - avoid_indoor: bool = proto.Field( - proto.BOOL, - number=4, - ) - vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_vehicle_info.VehicleInfo, - ) - toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( - proto.ENUM, - number=6, - enum=gmr_toll_passes.TollPass, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py deleted file mode 100644 index 14d466006fae..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteTravelMode', - }, -) - - -class RouteTravelMode(proto.Enum): - r"""A set of values used to specify the mode of travel. NOTE: WALK, - BICYCLE, and TWO_WHEELER routes are in beta and might sometimes be - missing clear sidewalks, pedestrian paths, or bicycling paths. You - must display this warning to the user for all walking, bicycling, - and two-wheel routes that you display in your app. - - Values: - TRAVEL_MODE_UNSPECIFIED (0): - No travel mode specified. Defaults to ``DRIVE``. - DRIVE (1): - Travel by passenger car. - BICYCLE (2): - Travel by bicycle. - WALK (3): - Travel by walking. - TWO_WHEELER (4): - Two-wheeled, motorized vehicle. For example, motorcycle. - Note that this differs from the ``BICYCLE`` travel mode - which covers human-powered mode. - """ - TRAVEL_MODE_UNSPECIFIED = 0 - DRIVE = 1 - BICYCLE = 2 - WALK = 3 - TWO_WHEELER = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py deleted file mode 100644 index b0dc2a6a0879..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py +++ /dev/null @@ -1,541 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import fallback_info as gmr_fallback_info -from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routing_preference as gmr_routing_preference -from google.maps.routing_v2.types import units as gmr_units -from google.maps.routing_v2.types import waypoint as gmr_waypoint -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteMatrixElementCondition', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'ComputeRouteMatrixRequest', - 'RouteMatrixOrigin', - 'RouteMatrixDestination', - 'RouteMatrixElement', - }, -) - - -class RouteMatrixElementCondition(proto.Enum): - r"""The condition of the route being returned. - - Values: - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): - Only used when the ``status`` of the element is not OK. - ROUTE_EXISTS (1): - A route was found, and the corresponding - information was filled out for the element. - ROUTE_NOT_FOUND (2): - No route could be found. Fields containing route - information, such as ``distance_meters`` or ``duration``, - will not be filled out in the element. - """ - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 - ROUTE_EXISTS = 1 - ROUTE_NOT_FOUND = 2 - - -class ComputeRoutesRequest(proto.Message): - r"""ComputeRoutes request message. - - Attributes: - origin (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint. - destination (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint. - intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): - Optional. A set of waypoints along the route - (excluding terminal points), for either stopping - at or passing by. Up to 25 intermediate - waypoints are supported. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, then an error is returned. You can - specify this option only when the ``travel_mode`` is - ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. - polyline_quality (google.maps.routing_v2.types.PolylineQuality): - Optional. Specifies your preference for the - quality of the polyline. - polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): - Optional. Specifies the preferred encoding - for the polyline. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't - set this value, then this value defaults to the - time that you made the request. If you set this - value to a time that has already occurred, then - the request fails. - compute_alternative_routes (bool): - Optional. Specifies whether to calculate - alternate routes in addition to the route. No - alternative routes are returned for requests - that have intermediate waypoints. - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. A set of conditions to satisfy that - affect the way routes are calculated. - language_code (str): - Optional. The BCP-47 language code, such as "en-US" or - "sr-Latn". For more information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - See `Language - Support `__ - for the list of supported languages. When you don't provide - this value, the display language is inferred from the - location of the route request. - region_code (str): - Optional. The region code, specified as a ccTLD ("top-level - domain") two-character value. For more information see - https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains - units (google.maps.routing_v2.types.Units): - Optional. Specifies the units of measure for the display - fields. This includes the ``instruction`` field in - ``NavigationInstruction``. The units of measure used for the - route, leg, step distance, and duration are not affected by - this value. If you don't provide this value, then the - display units are inferred from the location of the request. - requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): - Optional. Specifies what reference routes to calculate as - part of the request in addition to the default route. A - reference route is a route with a different route - calculation objective than the default route. For example an - FUEL_EFFICIENT reference route calculation takes into - account various parameters that would generate an optimal - fuel efficient route. - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - """ - class ReferenceRoute(proto.Enum): - r"""A supported reference route on the ComputeRoutesRequest. - - Values: - REFERENCE_ROUTE_UNSPECIFIED (0): - Not used. Requests containing this value - fail. - FUEL_EFFICIENT (1): - Fuel efficient route. Routes labeled with - this value are determined to be optimized for - parameters such as fuel consumption. - """ - REFERENCE_ROUTE_UNSPECIFIED = 0 - FUEL_EFFICIENT = 1 - - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the route(s). - FUEL_CONSUMPTION (2): - Estimated fuel consumption for the route(s). - TRAFFIC_ON_POLYLINE (3): - Traffic aware polylines for the route(s). - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - FUEL_CONSUMPTION = 2 - TRAFFIC_ON_POLYLINE = 3 - - origin: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - destination: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_waypoint.Waypoint, - ) - intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=gmr_waypoint.Waypoint, - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=4, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=5, - enum=gmr_routing_preference.RoutingPreference, - ) - polyline_quality: polyline.PolylineQuality = proto.Field( - proto.ENUM, - number=6, - enum=polyline.PolylineQuality, - ) - polyline_encoding: polyline.PolylineEncoding = proto.Field( - proto.ENUM, - number=12, - enum=polyline.PolylineEncoding, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - compute_alternative_routes: bool = proto.Field( - proto.BOOL, - number=8, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=9, - message=gmr_route_modifiers.RouteModifiers, - ) - language_code: str = proto.Field( - proto.STRING, - number=10, - ) - region_code: str = proto.Field( - proto.STRING, - number=16, - ) - units: gmr_units.Units = proto.Field( - proto.ENUM, - number=11, - enum=gmr_units.Units, - ) - requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( - proto.ENUM, - number=14, - enum=ReferenceRoute, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=15, - enum=ExtraComputation, - ) - - -class ComputeRoutesResponse(proto.Message): - r"""ComputeRoutes the response message. - - Attributes: - routes (MutableSequence[google.maps.routing_v2.types.Route]): - Contains an array of computed routes (up to three) when you - specify compute_alternatives_routes, and contains just one - route when you don't. When this array contains multiple - entries, the first one is the most recommended route. If the - array is empty, then it means no route could be found. - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route results with all of the input - preferences, it may fallback to using a - different way of computation. When fallback mode - is used, this field contains detailed info about - the fallback response. Otherwise this field is - unset. - geocoding_results (google.maps.routing_v2.types.GeocodingResults): - Contains geocoding response info for - waypoints specified as addresses. - """ - - routes: MutableSequence[route.Route] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=route.Route, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_fallback_info.FallbackInfo, - ) - geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_geocoding_results.GeocodingResults, - ) - - -class ComputeRouteMatrixRequest(proto.Message): - r"""ComputeRouteMatrix request message - - Attributes: - origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): - Required. Array of origins, which determines the rows of the - response matrix. Several size restrictions apply to the - cardinality of origins and destinations: - - - The number of elements (origins × destinations) must be - no greater than 625 in any case. - - The number of elements (origins × destinations) must be - no greater than 100 if routing_preference is set to - ``TRAFFIC_AWARE_OPTIMAL``. - - The number of waypoints (origins + destinations) - specified as ``place_id`` must be no greater than 50. - destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): - Required. Array of destinations, which - determines the columns of the response matrix. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, an error is returned. You can specify - this option only when the ``travel_mode`` is ``DRIVE`` or - ``TWO_WHEELER``, otherwise the request fails. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't - set this value, this defaults to the time that - you made the request. If you set this value to a - time that has already occurred, the request - fails. - language_code (str): - Optional. The BCP-47 language code, such as "en-US" or - "sr-Latn". For more information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - See `Language - Support `__ - for the list of supported languages. When you don't provide - this value, the display language is inferred from the - location of the first origin. - region_code (str): - Optional. The region code, specified as a ccTLD ("top-level - domain") two-character value. For more information see - https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - """ - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the matrix element(s). - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - - origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteMatrixOrigin', - ) - destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='RouteMatrixDestination', - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=3, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=4, - enum=gmr_routing_preference.RoutingPreference, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - language_code: str = proto.Field( - proto.STRING, - number=6, - ) - region_code: str = proto.Field( - proto.STRING, - number=9, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=8, - enum=ExtraComputation, - ) - - -class RouteMatrixOrigin(proto.Message): - r"""A single origin for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. Modifiers for every route that - takes this as the origin - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_route_modifiers.RouteModifiers, - ) - - -class RouteMatrixDestination(proto.Message): - r"""A single destination for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - - -class RouteMatrixElement(proto.Message): - r"""Encapsulates route information computed for an - origin/destination pair in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - origin_index (int): - Zero-based index of the origin in the - request. - - This field is a member of `oneof`_ ``_origin_index``. - destination_index (int): - Zero-based index of the destination in the - request. - - This field is a member of `oneof`_ ``_destination_index``. - status (google.rpc.status_pb2.Status): - Error status code for this element. - condition (google.maps.routing_v2.types.RouteMatrixElementCondition): - Indicates whether the route was found or not. - Independent of status. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the route - without taking traffic conditions into - consideration. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. For - example: restriction information and toll - information - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route with the given preferences for - this particular origin/destination pair, it may - fall back to using a different mode of - computation. When fallback mode is used, this - field contains detailed information about the - fallback response. Otherwise this field is - unset. - """ - - origin_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - destination_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - condition: 'RouteMatrixElementCondition' = proto.Field( - proto.ENUM, - number=9, - enum='RouteMatrixElementCondition', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=4, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - travel_advisory: route.RouteTravelAdvisory = proto.Field( - proto.MESSAGE, - number=7, - message=route.RouteTravelAdvisory, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=8, - message=gmr_fallback_info.FallbackInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py deleted file mode 100644 index d7d3a75786b1..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py +++ /dev/null @@ -1,67 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RoutingPreference', - }, -) - - -class RoutingPreference(proto.Enum): - r"""A set of values that specify factors to take into - consideration when calculating the route. - - Values: - ROUTING_PREFERENCE_UNSPECIFIED (0): - No routing preference specified. Default to - ``TRAFFIC_UNAWARE``. - TRAFFIC_UNAWARE (1): - Computes routes without taking live traffic conditions into - consideration. Suitable when traffic conditions don't matter - or are not applicable. Using this value produces the lowest - latency. Note: For ``RouteTravelMode`` DRIVE and TWO_WHEELER - choice of route and duration are based on road network and - average time-independent traffic conditions. Results for a - given request may vary over time due to changes in the road - network, updated average traffic conditions, and the - distributed nature of the service. Results may also vary - between nearly-equivalent routes at any time or frequency. - TRAFFIC_AWARE (2): - Calculates routes taking live traffic conditions into - consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, - some optimizations are applied to significantly reduce - latency. - TRAFFIC_AWARE_OPTIMAL (3): - Calculates the routes taking live traffic - conditions into consideration, without applying - most performance optimizations. Using this value - produces the highest latency. - """ - ROUTING_PREFERENCE_UNSPECIFIED = 0 - TRAFFIC_UNAWARE = 1 - TRAFFIC_AWARE = 2 - TRAFFIC_AWARE_OPTIMAL = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py deleted file mode 100644 index 9a322fff1e94..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'SpeedReadingInterval', - }, -) - - -class SpeedReadingInterval(proto.Message): - r"""Traffic density indicator on a contiguous segment of a polyline or - path. Given a path with points P_0, P_1, ... , P_N (zero-based - index), the SpeedReadingInterval defines an interval and describes - its traffic using the following categories. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - start_polyline_point_index (int): - The starting index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_start_polyline_point_index``. - end_polyline_point_index (int): - The ending index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_end_polyline_point_index``. - speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): - Traffic speed in this interval. - """ - class Speed(proto.Enum): - r"""The classification of polyline speed based on traffic data. - - Values: - SPEED_UNSPECIFIED (0): - Default value. This value is unused. - NORMAL (1): - Normal speed, no slowdown is detected. - SLOW (2): - Slowdown detected, but no traffic jam formed. - TRAFFIC_JAM (3): - Traffic jam detected. - """ - SPEED_UNSPECIFIED = 0 - NORMAL = 1 - SLOW = 2 - TRAFFIC_JAM = 3 - - start_polyline_point_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - end_polyline_point_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - speed: Speed = proto.Field( - proto.ENUM, - number=3, - enum=Speed, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py deleted file mode 100644 index 3182bd03ac01..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.type import money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TollInfo', - }, -) - - -class TollInfo(proto.Message): - r"""Encapsulates toll information on a ``Route`` or on a ``RouteLeg``. - - Attributes: - estimated_price (MutableSequence[google.type.money_pb2.Money]): - The monetary amount of tolls for the - corresponding Route or RouteLeg. This list - contains a money amount for each currency that - is expected to be charged by the toll stations. - Typically this list will contain only one item - for routes with tolls in one currency. For - international trips, this list may contain - multiple items to reflect tolls in different - currencies. - """ - - estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=money_pb2.Money, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py deleted file mode 100644 index 05edb1a082c3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py +++ /dev/null @@ -1,348 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TollPass', - }, -) - - -class TollPass(proto.Enum): - r"""List of toll passes around the world that we support. - - Values: - TOLL_PASS_UNSPECIFIED (0): - Not used. If this value is used, then the - request fails. - AU_ETOLL_TAG (82): - Sydney toll pass. See additional details at - https://www.myetoll.com.au. - AU_EWAY_TAG (83): - Sydney toll pass. See additional details at - https://www.tollpay.com.au. - AU_LINKT (2): - Australia-wide toll pass. - See additional details at - https://www.linkt.com.au/. - AR_TELEPASE (3): - Argentina toll pass. See additional details - at https://telepase.com.ar - BR_AUTO_EXPRESO (81): - Brazil toll pass. See additional details at - https://www.autoexpreso.com - BR_CONECTCAR (7): - Brazil toll pass. See additional details at - https://conectcar.com. - BR_MOVE_MAIS (8): - Brazil toll pass. See additional details at - https://movemais.com. - BR_PASSA_RAPIDO (88): - Brazil toll pass. See additional details at - https://pasorapido.gob.do/ - BR_SEM_PARAR (9): - Brazil toll pass. See additional details at - https://www.semparar.com.br. - BR_TAGGY (10): - Brazil toll pass. See additional details at - https://taggy.com.br. - BR_VELOE (11): - Brazil toll pass. See additional details at - https://veloe.com.br/site/onde-usar. - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): - Canada to United States border crossing. - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): - Canada to United States border crossing. - CA_US_BLUE_WATER_EDGE_PASS (18): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_CONNEXION (19): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_NEXUS_CARD (20): - Canada to United States border crossing. - ID_E_TOLL (16): - Indonesia. - E-card provided by multiple banks used to pay - for tolls. All e-cards via banks are charged the - same so only one enum value is needed. E.g. - - Bank Mandiri - https://www.bankmandiri.co.id/e-money - BCA - https://www.bca.co.id/flazz - - BNI - https://www.bni.co.id/id-id/ebanking/tapcash - IN_FASTAG (78): - India. - IN_LOCAL_HP_PLATE_EXEMPT (79): - India, HP state plate exemption. - MX_IAVE (90): - Mexico toll pass. - https://iave.capufe.gob.mx/#/ - MX_PASE (91): - Mexico - https://www.pase.com.mx - MX_QUICKPASS (93): - Mexico - https://operadoravial.com/quick-pass/ - MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): - http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf - MX_TAG_IAVE (12): - Mexico - MX_TAG_TELEVIA (13): - Mexico toll pass company. One of many - operating in Mexico City. See additional details - at https://www.televia.com.mx. - MX_TELEVIA (92): - Mexico toll pass company. One of many - operating in Mexico City. - https://www.televia.com.mx - MX_VIAPASS (14): - Mexico toll pass. See additional details at - https://www.viapass.com.mx/viapass/web_home.aspx. - US_AL_FREEDOM_PASS (21): - AL, USA. - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): - AK, USA. - US_CA_FASTRAK (4): - CA, USA. - US_CA_FASTRAK_CAV_STICKER (86): - Indicates driver has any FasTrak pass in - addition to the DMV issued Clean Air Vehicle - (CAV) sticker. - https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml - US_CO_EXPRESSTOLL (23): - CO, USA. - US_CO_GO_PASS (24): - CO, USA. - US_DE_EZPASSDE (25): - DE, USA. - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): - FL, USA. - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): - FL, USA. - US_FL_EPASS (67): - FL, USA. - US_FL_GIBA_TOLL_PASS (68): - FL, USA. - US_FL_LEEWAY (69): - FL, USA. - US_FL_SUNPASS (70): - FL, USA. - US_FL_SUNPASS_PRO (71): - FL, USA. - US_IL_EZPASSIL (73): - IL, USA. - US_IL_IPASS (72): - IL, USA. - US_IN_EZPASSIN (26): - IN, USA. - US_KS_BESTPASS_HORIZON (27): - KS, USA. - US_KS_KTAG (28): - KS, USA. - US_KS_NATIONALPASS (29): - KS, USA. - US_KS_PREPASS_ELITEPASS (30): - KS, USA. - US_KY_RIVERLINK (31): - KY, USA. - US_LA_GEAUXPASS (32): - LA, USA. - US_LA_TOLL_TAG (33): - LA, USA. - US_MA_EZPASSMA (6): - MA, USA. - US_MD_EZPASSMD (34): - MD, USA. - US_ME_EZPASSME (35): - ME, USA. - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): - MI, USA. - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): - MI, USA. - US_MI_IQ_PROX_CARD (38): - MI, USA. - US_MI_MACKINAC_BRIDGE_MAC_PASS (39): - MI, USA. - US_MI_NEXPRESS_TOLL (40): - MI, USA. - US_MN_EZPASSMN (41): - MN, USA. - US_NC_EZPASSNC (42): - NC, USA. - US_NC_PEACH_PASS (87): - NC, USA. - US_NC_QUICK_PASS (43): - NC, USA. - US_NH_EZPASSNH (80): - NH, USA. - US_NJ_DOWNBEACH_EXPRESS_PASS (75): - NJ, USA. - US_NJ_EZPASSNJ (74): - NJ, USA. - US_NY_EXPRESSPASS (76): - NY, USA. - US_NY_EZPASSNY (77): - NY, USA. - US_OH_EZPASSOH (44): - OH, USA. - US_PA_EZPASSPA (45): - PA, USA. - US_RI_EZPASSRI (46): - RI, USA. - US_SC_PALPASS (47): - SC, USA. - US_TX_BANCPASS (48): - TX, USA. - US_TX_DEL_RIO_PASS (49): - TX, USA. - US_TX_EFAST_PASS (50): - TX, USA. - US_TX_EAGLE_PASS_EXPRESS_CARD (51): - TX, USA. - US_TX_EPTOLL (52): - TX, USA. - US_TX_EZ_CROSS (53): - TX, USA. - US_TX_EZTAG (54): - TX, USA. - US_TX_LAREDO_TRADE_TAG (55): - TX, USA. - US_TX_PLUSPASS (56): - TX, USA. - US_TX_TOLLTAG (57): - TX, USA. - US_TX_TXTAG (58): - TX, USA. - US_TX_XPRESS_CARD (59): - TX, USA. - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): - UT, USA. - US_VA_EZPASSVA (61): - VA, USA. - US_WA_BREEZEBY (17): - WA, USA. - US_WA_GOOD_TO_GO (1): - WA, USA. - US_WV_EZPASSWV (62): - WV, USA. - US_WV_MEMORIAL_BRIDGE_TICKETS (63): - WV, USA. - US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): - WV, USA. - """ - TOLL_PASS_UNSPECIFIED = 0 - AU_ETOLL_TAG = 82 - AU_EWAY_TAG = 83 - AU_LINKT = 2 - AR_TELEPASE = 3 - BR_AUTO_EXPRESO = 81 - BR_CONECTCAR = 7 - BR_MOVE_MAIS = 8 - BR_PASSA_RAPIDO = 88 - BR_SEM_PARAR = 9 - BR_TAGGY = 10 - BR_VELOE = 11 - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 - CA_US_BLUE_WATER_EDGE_PASS = 18 - CA_US_CONNEXION = 19 - CA_US_NEXUS_CARD = 20 - ID_E_TOLL = 16 - IN_FASTAG = 78 - IN_LOCAL_HP_PLATE_EXEMPT = 79 - MX_IAVE = 90 - MX_PASE = 91 - MX_QUICKPASS = 93 - MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 - MX_TAG_IAVE = 12 - MX_TAG_TELEVIA = 13 - MX_TELEVIA = 92 - MX_VIAPASS = 14 - US_AL_FREEDOM_PASS = 21 - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 - US_CA_FASTRAK = 4 - US_CA_FASTRAK_CAV_STICKER = 86 - US_CO_EXPRESSTOLL = 23 - US_CO_GO_PASS = 24 - US_DE_EZPASSDE = 25 - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 - US_FL_EPASS = 67 - US_FL_GIBA_TOLL_PASS = 68 - US_FL_LEEWAY = 69 - US_FL_SUNPASS = 70 - US_FL_SUNPASS_PRO = 71 - US_IL_EZPASSIL = 73 - US_IL_IPASS = 72 - US_IN_EZPASSIN = 26 - US_KS_BESTPASS_HORIZON = 27 - US_KS_KTAG = 28 - US_KS_NATIONALPASS = 29 - US_KS_PREPASS_ELITEPASS = 30 - US_KY_RIVERLINK = 31 - US_LA_GEAUXPASS = 32 - US_LA_TOLL_TAG = 33 - US_MA_EZPASSMA = 6 - US_MD_EZPASSMD = 34 - US_ME_EZPASSME = 35 - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 - US_MI_IQ_PROX_CARD = 38 - US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 - US_MI_NEXPRESS_TOLL = 40 - US_MN_EZPASSMN = 41 - US_NC_EZPASSNC = 42 - US_NC_PEACH_PASS = 87 - US_NC_QUICK_PASS = 43 - US_NH_EZPASSNH = 80 - US_NJ_DOWNBEACH_EXPRESS_PASS = 75 - US_NJ_EZPASSNJ = 74 - US_NY_EXPRESSPASS = 76 - US_NY_EZPASSNY = 77 - US_OH_EZPASSOH = 44 - US_PA_EZPASSPA = 45 - US_RI_EZPASSRI = 46 - US_SC_PALPASS = 47 - US_TX_BANCPASS = 48 - US_TX_DEL_RIO_PASS = 49 - US_TX_EFAST_PASS = 50 - US_TX_EAGLE_PASS_EXPRESS_CARD = 51 - US_TX_EPTOLL = 52 - US_TX_EZ_CROSS = 53 - US_TX_EZTAG = 54 - US_TX_LAREDO_TRADE_TAG = 55 - US_TX_PLUSPASS = 56 - US_TX_TOLLTAG = 57 - US_TX_TXTAG = 58 - US_TX_XPRESS_CARD = 59 - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 - US_VA_EZPASSVA = 61 - US_WA_BREEZEBY = 17 - US_WA_GOOD_TO_GO = 1 - US_WV_EZPASSWV = 62 - US_WV_MEMORIAL_BRIDGE_TICKETS = 63 - US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py deleted file mode 100644 index 93cfaf1ee04c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Units', - }, -) - - -class Units(proto.Enum): - r"""A set of values that specify the unit of measure used in the - display. - - Values: - UNITS_UNSPECIFIED (0): - Units of measure not specified. Defaults to - the unit of measure inferred from the request. - METRIC (1): - Metric units of measure. - IMPERIAL (2): - Imperial (English) units of measure. - """ - UNITS_UNSPECIFIED = 0 - METRIC = 1 - IMPERIAL = 2 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py deleted file mode 100644 index a94a99025c80..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'VehicleEmissionType', - }, -) - - -class VehicleEmissionType(proto.Enum): - r"""A set of values describing the vehicle's emission type. - Applies only to the DRIVE travel mode. - - Values: - VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): - No emission type specified. Default to - GASOLINE. - GASOLINE (1): - Gasoline/petrol fueled vehicle. - ELECTRIC (2): - Electricity powered vehicle. - HYBRID (3): - Hybrid fuel (such as gasoline + electric) - vehicle. - DIESEL (4): - Diesel fueled vehicle. - """ - VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 - GASOLINE = 1 - ELECTRIC = 2 - HYBRID = 3 - DIESEL = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py deleted file mode 100644 index 2d71bb0a70a0..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import vehicle_emission_type - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'VehicleInfo', - }, -) - - -class VehicleInfo(proto.Message): - r"""Encapsulates the vehicle information, such as the license - plate last character. - - Attributes: - emission_type (google.maps.routing_v2.types.VehicleEmissionType): - Describes the vehicle's emission type. - Applies only to the DRIVE travel mode. - """ - - emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( - proto.ENUM, - number=2, - enum=vehicle_emission_type.VehicleEmissionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py deleted file mode 100644 index c25013cfd086..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import location as gmr_location - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Waypoint', - }, -) - - -class Waypoint(proto.Message): - r"""Encapsulates a waypoint. Waypoints mark both the beginning - and end of a route, and include intermediate stops along the - route. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - location (google.maps.routing_v2.types.Location): - A point specified using geographic - coordinates, including an optional heading. - - This field is a member of `oneof`_ ``location_type``. - place_id (str): - The POI Place ID associated with the - waypoint. - - This field is a member of `oneof`_ ``location_type``. - address (str): - Human readable address or a plus code. - See https://plus.codes for details. - - This field is a member of `oneof`_ ``location_type``. - via (bool): - Marks this waypoint as a milestone rather a stopping point. - For each non-via waypoint in the request, the response - appends an entry to the ``legs`` array to provide the - details for stopovers on that leg of the trip. Set this - value to true when you want the route to pass through this - waypoint without stopping over. Via waypoints don't cause an - entry to be added to the ``legs`` array, but they do route - the journey through the waypoint. You can only set this - value on waypoints that are intermediates. The request fails - if you set this field on terminal waypoints. If - ``ComputeRoutesRequest.optimize_waypoint_order`` is set to - true then this field cannot be set to true; otherwise, the - request fails. - vehicle_stopover (bool): - Indicates that the waypoint is meant for vehicles to stop - at, where the intention is to either pickup or drop-off. - When you set this value, the calculated route won't include - non-\ ``via`` waypoints on roads that are unsuitable for - pickup and drop-off. This option works only for ``DRIVE`` - and ``TWO_WHEELER`` travel modes, and when the - ``location_type`` is ``location``. - side_of_road (bool): - Indicates that the location of this waypoint is meant to - have a preference for the vehicle to stop at a particular - side of road. When you set this value, the route will pass - through the location so that the vehicle can stop at the - side of road that the location is biased towards from the - center of the road. This option works only for 'DRIVE' and - 'TWO_WHEELER' travel modes. - """ - - location: gmr_location.Location = proto.Field( - proto.MESSAGE, - number=1, - oneof='location_type', - message=gmr_location.Location, - ) - place_id: str = proto.Field( - proto.STRING, - number=2, - oneof='location_type', - ) - address: str = proto.Field( - proto.STRING, - number=7, - oneof='location_type', - ) - via: bool = proto.Field( - proto.BOOL, - number=3, - ) - vehicle_stopover: bool = proto.Field( - proto.BOOL, - number=4, - ) - side_of_road: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py deleted file mode 100644 index 59757e684c85..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/routing_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py deleted file mode 100644 index 381f53f7a26e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py deleted file mode 100644 index 125691404b0b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py deleted file mode 100644 index c978c3e55cd7..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py deleted file mode 100644 index ca13730e4ddc..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json deleted file mode 100644 index b5ed5aca319c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json +++ /dev/null @@ -1,321 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.routing.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-maps-routing", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_route_matrix_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_route_matrix_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_routes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_routes_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py deleted file mode 100644 index ab8c9f6352a2..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class routingCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'language_code', 'region_code', 'extra_computations', ), - 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'region_code', 'units', 'requested_reference_routes', 'extra_computations', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=routingCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the routing client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py deleted file mode 100644 index b93d9d947fd8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-maps-routing' - - -description = "Google Maps Routing API client library" - -version = {} -with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "google-geo-type >= 0.1.0, <1.0.0dev", -] -url = "https://github.com/googleapis/python-maps-routing" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.maps"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt deleted file mode 100644 index 33ac865954a6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 -google-geo-type==0.1.0 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py deleted file mode 100644 index 55f7b3a4ba31..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py +++ /dev/null @@ -1,1750 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.maps.routing_v2.services.routes import RoutesAsyncClient -from google.maps.routing_v2.services.routes import RoutesClient -from google.maps.routing_v2.services.routes import transports -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routes_service -from google.maps.routing_v2.types import routing_preference -from google.maps.routing_v2.types import toll_passes -from google.maps.routing_v2.types import units -from google.maps.routing_v2.types import vehicle_emission_type -from google.maps.routing_v2.types import vehicle_info -from google.maps.routing_v2.types import waypoint -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -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 RoutesClient._get_default_mtls_endpoint(None) is None - assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RoutesGrpcTransport, "grpc"), - (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RoutesRestTransport, "rest"), -]) -def test_routes_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -def test_routes_client_get_transport_class(): - transport = RoutesClient.get_transport_class() - available_transports = [ - transports.RoutesGrpcTransport, - transports.RoutesRestTransport, - ] - assert transport in available_transports - - transport = RoutesClient.get_transport_class("grpc") - assert transport == transports.RoutesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -def test_routes_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RoutesClient, transports.RoutesRestTransport, "rest", "true"), - (RoutesClient, transports.RoutesRestTransport, "rest", "false"), -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_routes_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - RoutesClient, RoutesAsyncClient -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -def test_routes_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -def test_routes_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RoutesClient, transports.RoutesRestTransport, "rest", None), -]) -def test_routes_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_routes_client_client_options_from_dict(): - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RoutesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_routes_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "routes.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes(request_type, transport: str = 'grpc'): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = routes_service.ComputeRoutesResponse( - ) - response = client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - client.compute_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - -@pytest.mark.asyncio -async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( - )) - response = await client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -@pytest.mark.asyncio -async def test_compute_routes_async_from_dict(): - await test_compute_routes_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix(request_type, transport: str = 'grpc'): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([routes_service.RouteMatrixElement()]) - response = client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, routes_service.RouteMatrixElement) - - -def test_compute_route_matrix_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - client.compute_route_matrix() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - -@pytest.mark.asyncio -async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) - response = await client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, routes_service.RouteMatrixElement) - - -@pytest.mark.asyncio -async def test_compute_route_matrix_async_from_dict(): - await test_compute_route_matrix_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes_rest(request_type): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = routes_service.ComputeRoutesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.compute_routes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): - transport_class = transports.RoutesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.ComputeRoutesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.compute_routes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_routes_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_routes._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_routes_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) - - request = routes_service.ComputeRoutesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.ComputeRoutesResponse() - - client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compute_routes_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRoutesRequest): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.compute_routes(request) - - -def test_compute_routes_rest_error(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix_rest(request_type): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = routes_service.RouteMatrixElement( - origin_index=1279, - destination_index=1817, - condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, - distance_meters=1594, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - json_return_value = "[{}]".format(json_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.compute_route_matrix(request) - - assert isinstance(response, Iterable) - response = next(response) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.RouteMatrixElement) - assert response.origin_index == 1279 - assert response.destination_index == 1817 - assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS - assert response.distance_meters == 1594 - - -def test_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): - transport_class = transports.RoutesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.RouteMatrixElement() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - json_return_value = "[{}]".format(json_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.compute_route_matrix(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_route_matrix_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_route_matrix_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) - req.return_value._content = "[{}]".format(req.return_value._content) - - request = routes_service.ComputeRouteMatrixRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.RouteMatrixElement() - - client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compute_route_matrix_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.compute_route_matrix(request) - - -def test_compute_route_matrix_rest_error(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RoutesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RoutesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = RoutesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RoutesGrpcTransport, - ) - -def test_routes_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_routes_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'compute_routes', - 'compute_route_matrix', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_routes_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -def test_routes_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport() - adc.assert_called_once() - - -def test_routes_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - RoutesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - ], -) -def test_routes_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, - ], -) -def test_routes_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.RoutesGrpcTransport, grpc_helpers), - (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_routes_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "routes.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_routes_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.RoutesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_routes_host_no_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_routes_host_with_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_routes_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RoutesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RoutesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.compute_routes._session - session2 = client2.transport.compute_routes._session - assert session1 != session2 - session1 = client1.transport.compute_route_matrix._session - session2 = client2.transport.compute_route_matrix._session - assert session1 != session2 -def test_routes_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_routes_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - 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 - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - 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=cred, - credentials_file=None, - scopes=None, - 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 - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_transport_channel_mtls_with_adc( - transport_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), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - 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 - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RoutesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = RoutesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = RoutesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = RoutesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RoutesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = RoutesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = RoutesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = RoutesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RoutesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = RoutesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: - transport_class = RoutesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (RoutesClient, transports.RoutesGrpcTransport), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py index 8324d3b000e0..cec054a68b9d 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py @@ -116,6 +116,10 @@ class ComputeRoutesRequest(proto.Message): for the list of supported languages. When you don't provide this value, the display language is inferred from the location of the route request. + region_code (str): + Optional. The region code, specified as a ccTLD ("top-level + domain") two-character value. For more information see + https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains units (google.maps.routing_v2.types.Units): Optional. Specifies the units of measure for the display fields. This includes the ``instruction`` field in @@ -227,6 +231,10 @@ class ExtraComputation(proto.Enum): proto.STRING, number=10, ) + region_code: str = proto.Field( + proto.STRING, + number=16, + ) units: gmr_units.Units = proto.Field( proto.ENUM, number=11, @@ -319,6 +327,19 @@ class ComputeRouteMatrixRequest(proto.Message): you made the request. If you set this value to a time that has already occurred, the request fails. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + See `Language + Support `__ + for the list of supported languages. When you don't provide + this value, the display language is inferred from the + location of the first origin. + region_code (str): + Optional. The region code, specified as a ccTLD ("top-level + domain") two-character value. For more information see + https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): Optional. A list of extra computations which may be used to complete the request. Note: These @@ -366,6 +387,14 @@ class ExtraComputation(proto.Enum): number=5, message=timestamp_pb2.Timestamp, ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + region_code: str = proto.Field( + proto.STRING, + number=9, + ) extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( proto.ENUM, number=8, diff --git a/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py b/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py index 291c4ea93db5..ab8c9f6352a2 100644 --- a/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py +++ b/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py @@ -39,8 +39,8 @@ def partition( class routingCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'extra_computations', ), - 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'units', 'requested_reference_routes', 'extra_computations', ), + 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'language_code', 'region_code', 'extra_computations', ), + 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'region_code', 'units', 'requested_reference_routes', 'extra_computations', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: From 294eb9d5cb12251b27d62e2d262702db21240824 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 22 Mar 2023 00:51:40 +0000 Subject: [PATCH 09/12] feat!: moved speed in SpeedReadingInterval into a oneof speed_type, this is a breaking change for Go client libraries docs: update proto comments to contain concrete references to other proto messages PiperOrigin-RevId: 518398192 Source-Link: https://github.com/googleapis/googleapis/commit/5dbc2b25ab939710ec0d4466323da6682a6cd40d Source-Link: https://github.com/googleapis/googleapis-gen/commit/e6636a863e3622c962cebcb6fbbec1a986315867 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcm91dGluZy8uT3dsQm90LnlhbWwiLCJoIjoiZTY2MzZhODYzZTM2MjJjOTYyY2ViY2I2ZmJiZWMxYTk4NjMxNTg2NyJ9 --- .../google-maps-routing/v2/.coveragerc | 13 + .../google-maps-routing/v2/.flake8 | 33 + .../google-maps-routing/v2/MANIFEST.in | 2 + .../google-maps-routing/v2/README.rst | 49 + .../google-maps-routing/v2/docs/conf.py | 376 ++++ .../google-maps-routing/v2/docs/index.rst | 7 + .../v2/docs/routing_v2/routes.rst | 6 + .../v2/docs/routing_v2/services.rst | 6 + .../v2/docs/routing_v2/types.rst | 6 + .../v2/google/maps/routing/__init__.py | 97 + .../v2/google/maps/routing/gapic_version.py | 16 + .../v2/google/maps/routing/py.typed | 2 + .../v2/google/maps/routing_v2/__init__.py | 98 + .../maps/routing_v2/gapic_metadata.json | 58 + .../google/maps/routing_v2/gapic_version.py | 16 + .../v2/google/maps/routing_v2/py.typed | 2 + .../maps/routing_v2/services/__init__.py | 15 + .../routing_v2/services/routes/__init__.py | 22 + .../services/routes/async_client.py | 416 ++++ .../maps/routing_v2/services/routes/client.py | 613 ++++++ .../services/routes/transports/__init__.py | 38 + .../services/routes/transports/base.py | 161 ++ .../services/routes/transports/grpc.py | 363 ++++ .../routes/transports/grpc_asyncio.py | 362 ++++ .../services/routes/transports/rest.py | 417 ++++ .../google/maps/routing_v2/types/__init__.py | 105 + .../maps/routing_v2/types/fallback_info.py | 105 + .../routing_v2/types/geocoding_results.py | 127 ++ .../google/maps/routing_v2/types/location.py | 63 + .../google/maps/routing_v2/types/maneuver.py | 96 + .../types/navigation_instruction.py | 58 + .../google/maps/routing_v2/types/polyline.py | 113 ++ .../v2/google/maps/routing_v2/types/route.py | 411 ++++ .../maps/routing_v2/types/route_label.py | 58 + .../maps/routing_v2/types/route_modifiers.py | 98 + .../routing_v2/types/route_travel_mode.py | 59 + .../maps/routing_v2/types/routes_service.py | 544 +++++ .../routing_v2/types/routing_preference.py | 69 + .../types/speed_reading_interval.py | 92 + .../google/maps/routing_v2/types/toll_info.py | 57 + .../maps/routing_v2/types/toll_passes.py | 351 ++++ .../v2/google/maps/routing_v2/types/units.py | 49 + .../routing_v2/types/vehicle_emission_type.py | 56 + .../maps/routing_v2/types/vehicle_info.py | 50 + .../google/maps/routing_v2/types/waypoint.py | 126 ++ .../google-maps-routing/v2/mypy.ini | 3 + .../google-maps-routing/v2/noxfile.py | 184 ++ ...rated_routes_compute_route_matrix_async.py | 52 + ...erated_routes_compute_route_matrix_sync.py | 52 + ...2_generated_routes_compute_routes_async.py | 51 + ...v2_generated_routes_compute_routes_sync.py | 51 + ...ippet_metadata_google.maps.routing.v2.json | 321 +++ .../v2/scripts/fixup_routing_v2_keywords.py | 177 ++ .../google-maps-routing/v2/setup.py | 91 + .../v2/testing/constraints-3.10.txt | 7 + .../v2/testing/constraints-3.11.txt | 7 + .../v2/testing/constraints-3.12.txt | 7 + .../v2/testing/constraints-3.7.txt | 10 + .../v2/testing/constraints-3.8.txt | 7 + .../v2/testing/constraints-3.9.txt | 7 + .../google-maps-routing/v2/tests/__init__.py | 16 + .../v2/tests/unit/__init__.py | 16 + .../v2/tests/unit/gapic/__init__.py | 16 + .../tests/unit/gapic/routing_v2/__init__.py | 16 + .../unit/gapic/routing_v2/test_routes.py | 1750 +++++++++++++++++ 65 files changed, 8722 insertions(+) create mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc create mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 create mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py create mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini create mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py create mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json create mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py create mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py create mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py diff --git a/owl-bot-staging/google-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc new file mode 100644 index 000000000000..d0ce5597b0a9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/routing/__init__.py + google/maps/routing/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/.flake8 @@ -0,0 +1,33 @@ +# -*- 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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in new file mode 100644 index 000000000000..c5b56c111c00 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/routing *.py +recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst new file mode 100644 index 000000000000..f0002366e552 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Routing API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Maps Routing API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py new file mode 100644 index 000000000000..d7a10abed96b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-maps-routing documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +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"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-maps-routing" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# 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"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# 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 + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +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 = { + "description": "Google Maps Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# 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 + +# 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 + +# 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, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# 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 = [] + +# 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' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is 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 = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# 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' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# 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' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-maps-routing-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- 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', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-maps-routing.tex", + u"google-maps-routing 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 + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# 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 = [ + ( + root_doc, + "google-maps-routing", + u"Google Maps Routing Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-maps-routing", + u"google-maps-routing Documentation", + author, + "google-maps-routing", + "GAPIC library for Google Maps Routing API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# 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), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst new file mode 100644 index 000000000000..e2563dd88ee9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + routing_v2/services + routing_v2/types diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst new file mode 100644 index 000000000000..3d52309cddae --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst @@ -0,0 +1,6 @@ +Routes +------------------------ + +.. automodule:: google.maps.routing_v2.services.routes + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst new file mode 100644 index 000000000000..e96568dc434c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst @@ -0,0 +1,6 @@ +Services for Google Maps Routing v2 API +======================================= +.. toctree:: + :maxdepth: 2 + + routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst new file mode 100644 index 000000000000..176a5a812cf8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst @@ -0,0 +1,6 @@ +Types for Google Maps Routing v2 API +==================================== + +.. automodule:: google.maps.routing_v2.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py new file mode 100644 index 000000000000..59020a3484c3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.maps.routing import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.routing_v2.services.routes.client import RoutesClient +from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient + +from google.maps.routing_v2.types.fallback_info import FallbackInfo +from google.maps.routing_v2.types.fallback_info import FallbackReason +from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode +from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint +from google.maps.routing_v2.types.geocoding_results import GeocodingResults +from google.maps.routing_v2.types.location import Location +from google.maps.routing_v2.types.maneuver import Maneuver +from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction +from google.maps.routing_v2.types.polyline import Polyline +from google.maps.routing_v2.types.polyline import PolylineEncoding +from google.maps.routing_v2.types.polyline import PolylineQuality +from google.maps.routing_v2.types.route import Route +from google.maps.routing_v2.types.route import RouteLeg +from google.maps.routing_v2.types.route import RouteLegStep +from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory +from google.maps.routing_v2.types.route import RouteLegTravelAdvisory +from google.maps.routing_v2.types.route import RouteTravelAdvisory +from google.maps.routing_v2.types.route_label import RouteLabel +from google.maps.routing_v2.types.route_modifiers import RouteModifiers +from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode +from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest +from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse +from google.maps.routing_v2.types.routes_service import RouteMatrixDestination +from google.maps.routing_v2.types.routes_service import RouteMatrixElement +from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin +from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition +from google.maps.routing_v2.types.routing_preference import RoutingPreference +from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval +from google.maps.routing_v2.types.toll_info import TollInfo +from google.maps.routing_v2.types.toll_passes import TollPass +from google.maps.routing_v2.types.units import Units +from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType +from google.maps.routing_v2.types.vehicle_info import VehicleInfo +from google.maps.routing_v2.types.waypoint import Waypoint + +__all__ = ('RoutesClient', + 'RoutesAsyncClient', + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py new file mode 100644 index 000000000000..405b1cebcf15 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py new file mode 100644 index 000000000000..cd9d694f63c6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.maps.routing_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.routes import RoutesClient +from .services.routes import RoutesAsyncClient + +from .types.fallback_info import FallbackInfo +from .types.fallback_info import FallbackReason +from .types.fallback_info import FallbackRoutingMode +from .types.geocoding_results import GeocodedWaypoint +from .types.geocoding_results import GeocodingResults +from .types.location import Location +from .types.maneuver import Maneuver +from .types.navigation_instruction import NavigationInstruction +from .types.polyline import Polyline +from .types.polyline import PolylineEncoding +from .types.polyline import PolylineQuality +from .types.route import Route +from .types.route import RouteLeg +from .types.route import RouteLegStep +from .types.route import RouteLegStepTravelAdvisory +from .types.route import RouteLegTravelAdvisory +from .types.route import RouteTravelAdvisory +from .types.route_label import RouteLabel +from .types.route_modifiers import RouteModifiers +from .types.route_travel_mode import RouteTravelMode +from .types.routes_service import ComputeRouteMatrixRequest +from .types.routes_service import ComputeRoutesRequest +from .types.routes_service import ComputeRoutesResponse +from .types.routes_service import RouteMatrixDestination +from .types.routes_service import RouteMatrixElement +from .types.routes_service import RouteMatrixOrigin +from .types.routes_service import RouteMatrixElementCondition +from .types.routing_preference import RoutingPreference +from .types.speed_reading_interval import SpeedReadingInterval +from .types.toll_info import TollInfo +from .types.toll_passes import TollPass +from .types.units import Units +from .types.vehicle_emission_type import VehicleEmissionType +from .types.vehicle_info import VehicleInfo +from .types.waypoint import Waypoint + +__all__ = ( + 'RoutesAsyncClient', +'ComputeRouteMatrixRequest', +'ComputeRoutesRequest', +'ComputeRoutesResponse', +'FallbackInfo', +'FallbackReason', +'FallbackRoutingMode', +'GeocodedWaypoint', +'GeocodingResults', +'Location', +'Maneuver', +'NavigationInstruction', +'Polyline', +'PolylineEncoding', +'PolylineQuality', +'Route', +'RouteLabel', +'RouteLeg', +'RouteLegStep', +'RouteLegStepTravelAdvisory', +'RouteLegTravelAdvisory', +'RouteMatrixDestination', +'RouteMatrixElement', +'RouteMatrixElementCondition', +'RouteMatrixOrigin', +'RouteModifiers', +'RouteTravelAdvisory', +'RouteTravelMode', +'RoutesClient', +'RoutingPreference', +'SpeedReadingInterval', +'TollInfo', +'TollPass', +'Units', +'VehicleEmissionType', +'VehicleInfo', +'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json new file mode 100644 index 000000000000..8382cea1d39a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json @@ -0,0 +1,58 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.routing_v2", + "protoPackage": "google.maps.routing.v2", + "schema": "1.0", + "services": { + "Routes": { + "clients": { + "grpc": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RoutesAsyncClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + }, + "rest": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "compute_route_matrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "compute_routes" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py new file mode 100644 index 000000000000..405b1cebcf15 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed new file mode 100644 index 000000000000..d62a4b821347 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py new file mode 100644 index 000000000000..e8e1c3845db5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py new file mode 100644 index 000000000000..ff3f8f71863f --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RoutesClient +from .async_client import RoutesAsyncClient + +__all__ = ( + 'RoutesClient', + 'RoutesAsyncClient', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py new file mode 100644 index 000000000000..7f8df74a140b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union + +from google.maps.routing_v2 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .client import RoutesClient + + +class RoutesAsyncClient: + """The Routes API.""" + + _client: RoutesClient + + DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RoutesClient.common_folder_path) + parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) + common_organization_path = staticmethod(RoutesClient.common_organization_path) + parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) + common_project_path = staticmethod(RoutesClient.common_project_path) + parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) + common_location_path = staticmethod(RoutesClient.common_location_path) + parse_common_location_path = staticmethod(RoutesClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesAsyncClient: The constructed client. + """ + return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(RoutesClient).get_transport_class, type(RoutesClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RoutesTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RoutesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RoutesClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # Create or coerce a protobuf request object. + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compute_routes, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + # Create or coerce a protobuf request object. + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.compute_route_matrix, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RoutesAsyncClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py new file mode 100644 index 000000000000..1943383c7246 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py @@ -0,0 +1,613 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast + +from google.maps.routing_v2 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import routes_service +from google.protobuf import duration_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RoutesGrpcTransport +from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport +from .transports.rest import RoutesRestTransport + + +class RoutesClientMeta(type): + """Metaclass for the Routes client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] + _transport_registry["grpc"] = RoutesGrpcTransport + _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport + _transport_registry["rest"] = RoutesRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RoutesTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RoutesClient(metaclass=RoutesClientMeta): + """The Routes API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "routes.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RoutesClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RoutesTransport: + """Returns the transport used by the client instance. + + Returns: + RoutesTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RoutesTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, RoutesTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RoutesTransport): + # transport is a RoutesTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def compute_routes(self, + request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> routes_service.ComputeRoutesResponse: + r"""Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.maps.routing_v2.types.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a routes_service.ComputeRoutesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, routes_service.ComputeRoutesRequest): + request = routes_service.ComputeRoutesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_routes] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_route_matrix(self, + request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> Iterable[routes_service.RouteMatrixElement]: + r"""Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routing_v2 + + def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + Iterable[google.maps.routing_v2.types.RouteMatrixElement]: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a routes_service.ComputeRouteMatrixRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, routes_service.ComputeRouteMatrixRequest): + request = routes_service.ComputeRouteMatrixRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RoutesClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RoutesClient", +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py new file mode 100644 index 000000000000..a15967f001c9 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RoutesTransport +from .grpc import RoutesGrpcTransport +from .grpc_asyncio import RoutesGrpcAsyncIOTransport +from .rest import RoutesRestTransport +from .rest import RoutesRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] +_transport_registry['grpc'] = RoutesGrpcTransport +_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport +_transport_registry['rest'] = RoutesRestTransport + +__all__ = ( + 'RoutesTransport', + 'RoutesGrpcTransport', + 'RoutesGrpcAsyncIOTransport', + 'RoutesRestTransport', + 'RoutesRestInterceptor', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py new file mode 100644 index 000000000000..a6fa68993eca --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.maps.routing_v2 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.maps.routing_v2.types import routes_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class RoutesTransport(abc.ABC): + """Abstract transport class for Routes.""" + + AUTH_SCOPES = ( + ) + + DEFAULT_HOST: str = 'routes.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.compute_routes: gapic_v1.method.wrap_method( + self.compute_routes, + default_timeout=None, + client_info=client_info, + ), + self.compute_route_matrix: gapic_v1.method.wrap_method( + self.compute_route_matrix, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Union[ + routes_service.ComputeRoutesResponse, + Awaitable[routes_service.ComputeRoutesResponse] + ]]: + raise NotImplementedError() + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Union[ + routes_service.RouteMatrixElement, + Awaitable[routes_service.RouteMatrixElement] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RoutesTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py new file mode 100644 index 000000000000..8316c8b03587 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py @@ -0,0 +1,363 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO + + +class RoutesGrpcTransport(RoutesTransport): + """gRPC backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + ~.ComputeRoutesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self.grpc_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + ~.RouteMatrixElement]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RoutesGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py new file mode 100644 index 000000000000..752c5eaefc33 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.maps.routing_v2.types import routes_service +from .base import RoutesTransport, DEFAULT_CLIENT_INFO +from .grpc import RoutesGrpcTransport + + +class RoutesGrpcAsyncIOTransport(RoutesTransport): + """gRPC AsyncIO backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + Awaitable[routes_service.ComputeRoutesResponse]]: + r"""Return a callable for the compute routes method over gRPC. + + Returns the primary route along with optional alternate routes, + given a set of terminal and intermediate waypoints. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using URL parameter ``$fields`` or ``fields``, or by using an + HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL + parameters and + headers `__. + The value is a comma separated list of field paths. See detailed + documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of Route-level duration, distance, and polyline + (an example production setup): + ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` + + Google discourage the use of the wildcard (``*``) response field + mask, or specifying the field mask at the top level + (``routes``), because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRoutesRequest], + Awaitable[~.ComputeRoutesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_routes' not in self._stubs: + self._stubs['compute_routes'] = self.grpc_channel.unary_unary( + '/google.maps.routing.v2.Routes/ComputeRoutes', + request_serializer=routes_service.ComputeRoutesRequest.serialize, + response_deserializer=routes_service.ComputeRoutesResponse.deserialize, + ) + return self._stubs['compute_routes'] + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + Awaitable[routes_service.RouteMatrixElement]]: + r"""Return a callable for the compute route matrix method over gRPC. + + Takes in a list of origins and destinations and returns a stream + containing route information for each combination of origin and + destination. + + **NOTE:** This method requires that you specify a response field + mask in the input. You can provide the response field mask by + using the URL parameter ``$fields`` or ``fields``, or by using + the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available + URL parameters and + headers `__. + The value is a comma separated list of field paths. See this + detailed documentation about `how to construct the field + paths `__. + + For example, in this method: + + - Field mask of all available fields (for manual inspection): + ``X-Goog-FieldMask: *`` + - Field mask of route durations, distances, element status, + condition, and element indices (an example production setup): + ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` + + It is critical that you include ``status`` in your field mask as + otherwise all messages will appear to be OK. Google discourages + the use of the wildcard (``*``) response field mask, because: + + - Selecting only the fields that you need helps our server save + computation cycles, allowing us to return the result to you + with a lower latency. + - Selecting only the fields that you need in your production + job ensures stable latency performance. We might add more + response fields in the future, and those new fields might + require extra computation time. If you select all fields, or + if you select all fields at the top level, then you might + experience performance degradation because any new field we + add will be automatically included in the response. + - Selecting only the fields that you need results in a smaller + response size, and thus higher network throughput. + + Returns: + Callable[[~.ComputeRouteMatrixRequest], + Awaitable[~.RouteMatrixElement]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'compute_route_matrix' not in self._stubs: + self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( + '/google.maps.routing.v2.Routes/ComputeRouteMatrix', + request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, + response_deserializer=routes_service.RouteMatrixElement.deserialize, + ) + return self._stubs['compute_route_matrix'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'RoutesGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py new file mode 100644 index 000000000000..c7fdf524b0c7 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.maps.routing_v2.types import routes_service + +from .base import RoutesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RoutesRestInterceptor: + """Interceptor for Routes. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RoutesRestTransport. + + .. code-block:: python + class MyCustomRoutesInterceptor(RoutesRestInterceptor): + def pre_compute_route_matrix(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_route_matrix(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_compute_routes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_routes(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) + client = RoutesClient(transport=transport) + + + """ + def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for compute_route_matrix + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for compute_routes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routes server. + """ + return request, metadata + + def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: + """Post-rpc interceptor for compute_routes + + Override in a subclass to manipulate the response + after it is returned by the Routes server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RoutesRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RoutesRestInterceptor + + +class RoutesRestTransport(RoutesTransport): + """REST backend transport for Routes. + + The Routes API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'routes.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[RoutesRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RoutesRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ComputeRouteMatrix(RoutesRestStub): + def __hash__(self): + return hash("ComputeRouteMatrix") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: routes_service.ComputeRouteMatrixRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> rest_streaming.ResponseIterator: + r"""Call the compute route matrix method over HTTP. + + Args: + request (~.routes_service.ComputeRouteMatrixRequest): + The request object. ComputeRouteMatrix request message + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.routes_service.RouteMatrixElement: + Encapsulates route information + computed for an origin/destination pair + in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/distanceMatrix/v2:computeRouteMatrix', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) + pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) + resp = self._interceptor.post_compute_route_matrix(resp) + return resp + + class _ComputeRoutes(RoutesRestStub): + def __hash__(self): + return hash("ComputeRoutes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: routes_service.ComputeRoutesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> routes_service.ComputeRoutesResponse: + r"""Call the compute routes method over HTTP. + + Args: + request (~.routes_service.ComputeRoutesRequest): + The request object. ComputeRoutes request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.routes_service.ComputeRoutesResponse: + ComputeRoutes the response message. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/directions/v2:computeRoutes', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_compute_routes(request, metadata) + pb_request = routes_service.ComputeRoutesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = routes_service.ComputeRoutesResponse() + pb_resp = routes_service.ComputeRoutesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_compute_routes(resp) + return resp + + @property + def compute_route_matrix(self) -> Callable[ + [routes_service.ComputeRouteMatrixRequest], + routes_service.RouteMatrixElement]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore + + @property + def compute_routes(self) -> Callable[ + [routes_service.ComputeRoutesRequest], + routes_service.ComputeRoutesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RoutesRestTransport', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py new file mode 100644 index 000000000000..7323899cfc30 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .fallback_info import ( + FallbackInfo, + FallbackReason, + FallbackRoutingMode, +) +from .geocoding_results import ( + GeocodedWaypoint, + GeocodingResults, +) +from .location import ( + Location, +) +from .navigation_instruction import ( + NavigationInstruction, +) +from .polyline import ( + Polyline, + PolylineEncoding, + PolylineQuality, +) +from .route import ( + Route, + RouteLeg, + RouteLegStep, + RouteLegStepTravelAdvisory, + RouteLegTravelAdvisory, + RouteTravelAdvisory, +) +from .route_modifiers import ( + RouteModifiers, +) +from .routes_service import ( + ComputeRouteMatrixRequest, + ComputeRoutesRequest, + ComputeRoutesResponse, + RouteMatrixDestination, + RouteMatrixElement, + RouteMatrixOrigin, + RouteMatrixElementCondition, +) +from .speed_reading_interval import ( + SpeedReadingInterval, +) +from .toll_info import ( + TollInfo, +) +from .vehicle_info import ( + VehicleInfo, +) +from .waypoint import ( + Waypoint, +) + +__all__ = ( + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'Units', + 'VehicleEmissionType', + 'VehicleInfo', + 'Waypoint', +) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py new file mode 100644 index 000000000000..51700720cfcd --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'FallbackReason', + 'FallbackRoutingMode', + 'FallbackInfo', + }, +) + + +class FallbackReason(proto.Enum): + r"""Reasons for using fallback response. + + Values: + FALLBACK_REASON_UNSPECIFIED (0): + No fallback reason specified. + SERVER_ERROR (1): + A server error happened while calculating + routes with your preferred routing mode, but we + were able to return a result calculated by an + alternative mode. + LATENCY_EXCEEDED (2): + We were not able to finish the calculation + with your preferred routing mode on time, but we + were able to return a result calculated by an + alternative mode. + """ + FALLBACK_REASON_UNSPECIFIED = 0 + SERVER_ERROR = 1 + LATENCY_EXCEEDED = 2 + + +class FallbackRoutingMode(proto.Enum): + r"""Actual routing mode used for returned fallback response. + + Values: + FALLBACK_ROUTING_MODE_UNSPECIFIED (0): + Not used. + FALLBACK_TRAFFIC_UNAWARE (1): + Indicates the ``TRAFFIC_UNAWARE`` + [google.maps.routing.v2.RoutingPreference] was used to + compute the response. + FALLBACK_TRAFFIC_AWARE (2): + Indicates the ``TRAFFIC_AWARE`` + [RoutingPreference][google.maps.routing.v2.RoutingPreference] + was used to compute the response. + """ + FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 + FALLBACK_TRAFFIC_UNAWARE = 1 + FALLBACK_TRAFFIC_AWARE = 2 + + +class FallbackInfo(proto.Message): + r"""Information related to how and why a fallback result was + used. If this field is set, then it means the server used a + different routing mode from your preferred mode as fallback. + + Attributes: + routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): + Routing mode used for the response. If + fallback was triggered, the mode may be + different from routing preference set in the + original client request. + reason (google.maps.routing_v2.types.FallbackReason): + The reason why fallback response was used + instead of the original response. This field is + only populated when the fallback mode is + triggered and the fallback response is returned. + """ + + routing_mode: 'FallbackRoutingMode' = proto.Field( + proto.ENUM, + number=1, + enum='FallbackRoutingMode', + ) + reason: 'FallbackReason' = proto.Field( + proto.ENUM, + number=2, + enum='FallbackReason', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py new file mode 100644 index 000000000000..577d97bc2e95 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'GeocodingResults', + 'GeocodedWaypoint', + }, +) + + +class GeocodingResults(proto.Message): + r"""Contains + [GeocodedWaypoints][google.maps.routing.v2.GeocodedWaypoint] for + origin, destination and intermediate waypoints. Only populated for + address waypoints. + + Attributes: + origin (google.maps.routing_v2.types.GeocodedWaypoint): + Origin geocoded waypoint. + destination (google.maps.routing_v2.types.GeocodedWaypoint): + Destination geocoded waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.GeocodedWaypoint]): + A list of intermediate geocoded waypoints + each containing an index field that corresponds + to the zero-based position of the waypoint in + the order they were specified in the request. + """ + + origin: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=1, + message='GeocodedWaypoint', + ) + destination: 'GeocodedWaypoint' = proto.Field( + proto.MESSAGE, + number=2, + message='GeocodedWaypoint', + ) + intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='GeocodedWaypoint', + ) + + +class GeocodedWaypoint(proto.Message): + r"""Details about the locations used as waypoints. Only populated + for address waypoints. Includes details about the geocoding + results for the purposes of determining what the address was + geocoded to. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + geocoder_status (google.rpc.status_pb2.Status): + Indicates the status code resulting from the + geocoding operation. + intermediate_waypoint_request_index (int): + The index of the corresponding intermediate + waypoint in the request. Only populated if the + corresponding waypoint is an intermediate + waypoint. + + This field is a member of `oneof`_ ``_intermediate_waypoint_request_index``. + type_ (MutableSequence[str]): + The type(s) of the result, in the form of + zero or more type tags. Supported types: + https://developers.google.com/maps/documentation/geocoding/requests-geocoding#Types + partial_match (bool): + Indicates that the geocoder did not return an + exact match for the original request, though it + was able to match part of the requested address. + You may wish to examine the original request for + misspellings and/or an incomplete address. + place_id (str): + The place ID for this result. + """ + + geocoder_status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + intermediate_waypoint_request_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + type_: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + partial_match: bool = proto.Field( + proto.BOOL, + number=4, + ) + place_id: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py new file mode 100644 index 000000000000..10724419f9a8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Location', + }, +) + + +class Location(proto.Message): + r"""Encapsulates a location (a geographic point, and an optional + heading). + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + The waypoint's geographic coordinates. + heading (google.protobuf.wrappers_pb2.Int32Value): + The compass heading associated with the direction of the + flow of traffic. This value is used to specify the side of + the road to use for pickup and drop-off. Heading values can + be from 0 to 360, where 0 specifies a heading of due North, + 90 specifies a heading of due East, etc. You can use this + field only for ``DRIVE`` and ``TWO_WHEELER`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + heading: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py new file mode 100644 index 000000000000..60e5cd3cb9c6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Maneuver', + }, +) + + +class Maneuver(proto.Enum): + r"""A set of values that specify the navigation action to take + for the current step (e.g., turn left, merge, straight, etc.). + + Values: + MANEUVER_UNSPECIFIED (0): + Not used. + TURN_SLIGHT_LEFT (1): + Turn slightly to the left. + TURN_SHARP_LEFT (2): + Turn sharply to the left. + UTURN_LEFT (3): + Make a left u-turn. + TURN_LEFT (4): + Turn left. + TURN_SLIGHT_RIGHT (5): + Turn slightly to the right. + TURN_SHARP_RIGHT (6): + Turn sharply to the right. + UTURN_RIGHT (7): + Make a right u-turn. + TURN_RIGHT (8): + Turn right. + STRAIGHT (9): + Go straight. + RAMP_LEFT (10): + Take the left ramp. + RAMP_RIGHT (11): + Take the right ramp. + MERGE (12): + Merge into traffic. + FORK_LEFT (13): + Take the left fork. + FORK_RIGHT (14): + Take the right fork. + FERRY (15): + Take the ferry. + FERRY_TRAIN (16): + Take the train leading onto the ferry. + ROUNDABOUT_LEFT (17): + Turn left at the roundabout. + ROUNDABOUT_RIGHT (18): + Turn right at the roundabout. + """ + MANEUVER_UNSPECIFIED = 0 + TURN_SLIGHT_LEFT = 1 + TURN_SHARP_LEFT = 2 + UTURN_LEFT = 3 + TURN_LEFT = 4 + TURN_SLIGHT_RIGHT = 5 + TURN_SHARP_RIGHT = 6 + UTURN_RIGHT = 7 + TURN_RIGHT = 8 + STRAIGHT = 9 + RAMP_LEFT = 10 + RAMP_RIGHT = 11 + MERGE = 12 + FORK_LEFT = 13 + FORK_RIGHT = 14 + FERRY = 15 + FERRY_TRAIN = 16 + ROUNDABOUT_LEFT = 17 + ROUNDABOUT_RIGHT = 18 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py new file mode 100644 index 000000000000..dc8b69e76ccd --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import maneuver as gmr_maneuver + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'NavigationInstruction', + }, +) + + +class NavigationInstruction(proto.Message): + r"""Encapsulates navigation instructions for a + [RouteLegStep][google.maps.routing.v2.RouteLegStep] + + Attributes: + maneuver (google.maps.routing_v2.types.Maneuver): + Encapsulates the navigation instructions for + the current step (e.g., turn left, merge, + straight, etc.). This field determines which + icon to display. + instructions (str): + Instructions for navigating this step. + """ + + maneuver: gmr_maneuver.Maneuver = proto.Field( + proto.ENUM, + number=1, + enum=gmr_maneuver.Maneuver, + ) + instructions: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py new file mode 100644 index 000000000000..4d9630691288 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'PolylineQuality', + 'PolylineEncoding', + 'Polyline', + }, +) + + +class PolylineQuality(proto.Enum): + r"""A set of values that specify the quality of the polyline. + + Values: + POLYLINE_QUALITY_UNSPECIFIED (0): + No polyline quality preference specified. Defaults to + ``OVERVIEW``. + HIGH_QUALITY (1): + Specifies a high-quality polyline - which is composed using + more points than ``OVERVIEW``, at the cost of increased + response size. Use this value when you need more precision. + OVERVIEW (2): + Specifies an overview polyline - which is composed using a + small number of points. Use this value when displaying an + overview of the route. Using this option has a lower request + latency compared to using the ``HIGH_QUALITY`` option. + """ + POLYLINE_QUALITY_UNSPECIFIED = 0 + HIGH_QUALITY = 1 + OVERVIEW = 2 + + +class PolylineEncoding(proto.Enum): + r"""Specifies the preferred type of polyline to be returned. + + Values: + POLYLINE_ENCODING_UNSPECIFIED (0): + No polyline type preference specified. Defaults to + ``ENCODED_POLYLINE``. + ENCODED_POLYLINE (1): + Specifies a polyline encoded using the `polyline encoding + algorithm `__. + GEO_JSON_LINESTRING (2): + Specifies a polyline using the `GeoJSON LineString + format `__ + """ + POLYLINE_ENCODING_UNSPECIFIED = 0 + ENCODED_POLYLINE = 1 + GEO_JSON_LINESTRING = 2 + + +class Polyline(proto.Message): + r"""Encapsulates an encoded polyline. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + encoded_polyline (str): + The string encoding of the polyline using the `polyline + encoding + algorithm `__ + + This field is a member of `oneof`_ ``polyline_type``. + geo_json_linestring (google.protobuf.struct_pb2.Struct): + Specifies a polyline using the `GeoJSON LineString + format `__ + + This field is a member of `oneof`_ ``polyline_type``. + """ + + encoded_polyline: str = proto.Field( + proto.STRING, + number=1, + oneof='polyline_type', + ) + geo_json_linestring: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + oneof='polyline_type', + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py new file mode 100644 index 000000000000..9c25ea98abc3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py @@ -0,0 +1,411 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.geo.type import viewport_pb2 # type: ignore +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction +from google.maps.routing_v2.types import polyline as gmr_polyline +from google.maps.routing_v2.types import route_label +from google.maps.routing_v2.types import speed_reading_interval +from google.maps.routing_v2.types import toll_info as gmr_toll_info +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Route', + 'RouteTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteLegStepTravelAdvisory', + 'RouteLeg', + 'RouteLegStep', + }, +) + + +class Route(proto.Message): + r"""Encapsulates a route, which consists of a series of connected + road segments that join beginning, ending, and intermediate + waypoints. + + Attributes: + route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): + Labels for the ``Route`` that are useful to identify + specific properties of the route to compare against others. + legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): + A collection of legs (path segments between waypoints) that + make-up the route. Each leg corresponds to the trip between + two non-\ ``via`` + [Waypoints][google.maps.routing.v2.Waypoint]. For example, a + route with no intermediate waypoints has only one leg. A + route that includes one non-\ ``via`` intermediate waypoint + has two legs. A route that includes one ``via`` intermediate + waypoint has one leg. The order of the legs matches the + order of Waypoints from ``origin`` to ``intermediates`` to + ``destination``. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this + value is the same as ``static_duration``. If you set the + ``routing_preference`` to either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the route + without taking traffic conditions into + consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall route polyline. This polyline will be the + combined polyline of all ``legs``. + description (str): + A description of the route. + warnings (MutableSequence[str]): + An array of warnings to show when displaying + the route. + viewport (google.geo.type.viewport_pb2.Viewport): + The viewport bounding box of the polyline. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. + route_token (str): + Web-safe base64 encoded route token that can be passed to + NavigationSDK, which allows the Navigation SDK to + reconstruct the route during navigation, and in the event of + rerouting honor the original intention when Routes + ComputeRoutes is called. Customers should treat this token + as an opaque blob. NOTE: ``Route.route_token`` is only + available for requests that have set + ``ComputeRoutesRequest.routing_preference`` to + ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. + ``Route.route_token`` is also not supported for requests + that have Via waypoints. + """ + + route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( + proto.ENUM, + number=13, + enum=route_label.RouteLabel, + ) + legs: MutableSequence['RouteLeg'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteLeg', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=2, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_polyline.Polyline, + ) + description: str = proto.Field( + proto.STRING, + number=6, + ) + warnings: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + viewport: viewport_pb2.Viewport = proto.Field( + proto.MESSAGE, + number=8, + message=viewport_pb2.Viewport, + ) + travel_advisory: 'RouteTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=9, + message='RouteTravelAdvisory', + ) + route_token: str = proto.Field( + proto.STRING, + number=12, + ) + + +class RouteTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction + etc. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Encapsulates information about tolls on the Route. This + field is only populated if we expect there are tolls on the + Route. If this field is set but the estimated_price subfield + is not populated, we expect that road contains tolls but we + do not know an estimated price. If this field is not set, + then we expect there is no toll on the Route. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the route without overlap. The + start point of a specified interval is the same as the end + point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + fuel_consumption_microliters (int): + The fuel consumption prediction in + microliters. + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=speed_reading_interval.SpeedReadingInterval, + ) + fuel_consumption_microliters: int = proto.Field( + proto.INT64, + number=5, + ) + + +class RouteLegTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction + etc. on a route leg. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Encapsulates information about tolls on the specific + RouteLeg. This field is only populated if we expect there + are tolls on the RouteLeg. If this field is set but the + estimated_price subfield is not populated, we expect that + road contains tolls but we do not know an estimated price. + If this field does not exist, then there is no toll on the + RouteLeg. + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + Speed reading intervals detailing traffic density. + Applicable in case of ``TRAFFIC_AWARE`` and + ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals + cover the entire polyline of the RouteLg without overlap. + The start point of a specified interval is the same as the + end point of the preceding interval. + + Example: + + :: + + polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + speed_reading_intervals: [A,C), [C,D), [D,G). + """ + + toll_info: gmr_toll_info.TollInfo = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_toll_info.TollInfo, + ) + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLegStepTravelAdvisory(proto.Message): + r"""Encapsulates the additional information that the user should + be informed about, such as possible traffic zone restriction on + a leg step. + + Attributes: + speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): + NOTE: This field is not currently populated. + """ + + speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=speed_reading_interval.SpeedReadingInterval, + ) + + +class RouteLeg(proto.Message): + r"""Encapsulates a segment between non-\ ``via`` waypoints. + + Attributes: + distance_meters (int): + The travel distance of the route leg, in + meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the leg. If the + ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then + this value is the same as ``static_duration``. If the + ``route_preference`` is either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the leg, + calculated without taking traffic conditions + into consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall polyline for this leg. This includes that each + ``step``'s polyline. + start_location (google.maps.routing_v2.types.Location): + The start location of this leg. This might be different from + the provided ``origin``. For example, when the provided + ``origin`` is not near a road, this is a point on the road. + end_location (google.maps.routing_v2.types.Location): + The end location of this leg. This might be different from + the provided ``destination``. For example, when the provided + ``destination`` is not near a road, this is a point on the + road. + steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): + An array of steps denoting segments within + this leg. Each step represents one navigation + instruction. + travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): + Encapsulates the additional information that + the user should be informed about, such as + possible traffic zone restriction etc. on a + route leg. + """ + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=4, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=6, + message=location.Location, + ) + steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='RouteLegStep', + ) + travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=8, + message='RouteLegTravelAdvisory', + ) + + +class RouteLegStep(proto.Message): + r"""Encapsulates a segment of a + [RouteLeg][google.maps.routing.v2.RouteLeg]. A step corresponds to a + single navigation instruction. Route legs are made up of steps. + + Attributes: + distance_meters (int): + The travel distance of this step, in meters. + In some circumstances, this field might not have + a value. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of travel through this step + without taking traffic conditions into + consideration. In some circumstances, this field + might not have a value. + polyline (google.maps.routing_v2.types.Polyline): + The polyline associated with this step. + start_location (google.maps.routing_v2.types.Location): + The start location of this step. + end_location (google.maps.routing_v2.types.Location): + The end location of this step. + navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): + Navigation instructions. + travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): + Encapsulates the additional information that + the user should be informed about, such as + possible traffic zone restriction on a leg step. + """ + + distance_meters: int = proto.Field( + proto.INT32, + number=1, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + polyline: gmr_polyline.Polyline = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_polyline.Polyline, + ) + start_location: location.Location = proto.Field( + proto.MESSAGE, + number=4, + message=location.Location, + ) + end_location: location.Location = proto.Field( + proto.MESSAGE, + number=5, + message=location.Location, + ) + navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( + proto.MESSAGE, + number=6, + message=gmr_navigation_instruction.NavigationInstruction, + ) + travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=7, + message='RouteLegStepTravelAdvisory', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py new file mode 100644 index 000000000000..e0105d9b95bd --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteLabel', + }, +) + + +class RouteLabel(proto.Enum): + r"""Labels for the [Route][google.maps.routing.v2.Route] that are useful + to identify specific properties of the route to compare against + others. + + Values: + ROUTE_LABEL_UNSPECIFIED (0): + Default - not used. + DEFAULT_ROUTE (1): + The default "best" route returned for the + route computation. + DEFAULT_ROUTE_ALTERNATE (2): + An alternative to the default "best" route. Routes like this + will be returned when + [compute_alternative_routes][google.maps.routing.v2.ComputeRoutesRequest.compute_alternative_routes] + is specified. + FUEL_EFFICIENT (3): + Fuel efficient route. Routes labeled with + this value are determined to be optimized for + Eco parameters such as fuel consumption. + """ + ROUTE_LABEL_UNSPECIFIED = 0 + DEFAULT_ROUTE = 1 + DEFAULT_ROUTE_ALTERNATE = 2 + FUEL_EFFICIENT = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py new file mode 100644 index 000000000000..589dc7c38f4a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import toll_passes as gmr_toll_passes +from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteModifiers', + }, +) + + +class RouteModifiers(proto.Message): + r"""Encapsulates a set of optional conditions to satisfy when + calculating the routes. + + Attributes: + avoid_tolls (bool): + Specifies whether to avoid toll roads where reasonable. + Preference will be given to routes not containing toll + roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + avoid_highways (bool): + Specifies whether to avoid highways where reasonable. + Preference will be given to routes not containing highways. + Applies only to the ``DRIVE`` and ``TWO_WHEELER`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + avoid_ferries (bool): + Specifies whether to avoid ferries where reasonable. + Preference will be given to routes not containing travel by + ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + avoid_indoor (bool): + Specifies whether to avoid navigating indoors where + reasonable. Preference will be given to routes not + containing indoor navigation. Applies only to the ``WALK`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + vehicle_info (google.maps.routing_v2.types.VehicleInfo): + Specifies the vehicle information. + toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): + Encapsulates information about toll passes. If toll passes + are provided, the API tries to return the pass price. If + toll passes are not provided, the API treats the toll pass + as unknown and tries to return the cash price. Applies only + to the ``DRIVE`` and ``TWO_WHEELER`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + """ + + avoid_tolls: bool = proto.Field( + proto.BOOL, + number=1, + ) + avoid_highways: bool = proto.Field( + proto.BOOL, + number=2, + ) + avoid_ferries: bool = proto.Field( + proto.BOOL, + number=3, + ) + avoid_indoor: bool = proto.Field( + proto.BOOL, + number=4, + ) + vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( + proto.MESSAGE, + number=5, + message=gmr_vehicle_info.VehicleInfo, + ) + toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( + proto.ENUM, + number=6, + enum=gmr_toll_passes.TollPass, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py new file mode 100644 index 000000000000..239957aada7f --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteTravelMode', + }, +) + + +class RouteTravelMode(proto.Enum): + r"""A set of values used to specify the mode of travel. NOTE: ``WALK``, + ``BICYCLE``, and ``TWO_WHEELER`` routes are in beta and might + sometimes be missing clear sidewalks, pedestrian paths, or bicycling + paths. You must display this warning to the user for all walking, + bicycling, and two-wheel routes that you display in your app. + + Values: + TRAVEL_MODE_UNSPECIFIED (0): + No travel mode specified. Defaults to ``DRIVE``. + DRIVE (1): + Travel by passenger car. + BICYCLE (2): + Travel by bicycle. + WALK (3): + Travel by walking. + TWO_WHEELER (4): + Two-wheeled, motorized vehicle. For example, motorcycle. + Note that this differs from the ``BICYCLE`` travel mode + which covers human-powered mode. + """ + TRAVEL_MODE_UNSPECIFIED = 0 + DRIVE = 1 + BICYCLE = 2 + WALK = 3 + TWO_WHEELER = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py new file mode 100644 index 000000000000..f95ca0ed0aca --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py @@ -0,0 +1,544 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import fallback_info as gmr_fallback_info +from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routing_preference as gmr_routing_preference +from google.maps.routing_v2.types import units as gmr_units +from google.maps.routing_v2.types import waypoint as gmr_waypoint +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RouteMatrixElementCondition', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'ComputeRouteMatrixRequest', + 'RouteMatrixOrigin', + 'RouteMatrixDestination', + 'RouteMatrixElement', + }, +) + + +class RouteMatrixElementCondition(proto.Enum): + r"""The condition of the route being returned. + + Values: + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): + Only used when the ``status`` of the element is not OK. + ROUTE_EXISTS (1): + A route was found, and the corresponding + information was filled out for the element. + ROUTE_NOT_FOUND (2): + No route could be found. Fields containing route + information, such as ``distance_meters`` or ``duration``, + will not be filled out in the element. + """ + ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 + ROUTE_EXISTS = 1 + ROUTE_NOT_FOUND = 2 + + +class ComputeRoutesRequest(proto.Message): + r"""ComputeRoutes request message. + + Attributes: + origin (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint. + destination (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint. + intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): + Optional. A set of waypoints along the route + (excluding terminal points), for either stopping + at or passing by. Up to 25 intermediate + waypoints are supported. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, then an error is returned. You can + specify this option only when the ``travel_mode`` is + ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. + polyline_quality (google.maps.routing_v2.types.PolylineQuality): + Optional. Specifies your preference for the + quality of the polyline. + polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): + Optional. Specifies the preferred encoding + for the polyline. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't + set this value, then this value defaults to the + time that you made the request. If you set this + value to a time that has already occurred, then + the request fails. + compute_alternative_routes (bool): + Optional. Specifies whether to calculate + alternate routes in addition to the route. No + alternative routes are returned for requests + that have intermediate waypoints. + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. A set of conditions to satisfy that + affect the way routes are calculated. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + See `Language + Support `__ + for the list of supported languages. When you don't provide + this value, the display language is inferred from the + location of the route request. + region_code (str): + Optional. The region code, specified as a ccTLD ("top-level + domain") two-character value. For more information see + https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains + units (google.maps.routing_v2.types.Units): + Optional. Specifies the units of measure for the display + fields. This includes the ``instruction`` field in + [NavigationInstruction][google.maps.routing.v2.NavigationInstruction]. + The units of measure used for the route, leg, step distance, + and duration are not affected by this value. If you don't + provide this value, then the display units are inferred from + the location of the request. + requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): + Optional. Specifies what reference routes to calculate as + part of the request in addition to the default route. A + reference route is a route with a different route + calculation objective than the default route. For example a + ``FUEL_EFFICIENT`` reference route calculation takes into + account various parameters that would generate an optimal + fuel efficient route. + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + """ + class ReferenceRoute(proto.Enum): + r"""A supported reference route on the ComputeRoutesRequest. + + Values: + REFERENCE_ROUTE_UNSPECIFIED (0): + Not used. Requests containing this value + fail. + FUEL_EFFICIENT (1): + Fuel efficient route. Routes labeled with + this value are determined to be optimized for + parameters such as fuel consumption. + """ + REFERENCE_ROUTE_UNSPECIFIED = 0 + FUEL_EFFICIENT = 1 + + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the route(s). + FUEL_CONSUMPTION (2): + Estimated fuel consumption for the route(s). + TRAFFIC_ON_POLYLINE (3): + Traffic aware polylines for the route(s). + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + FUEL_CONSUMPTION = 2 + TRAFFIC_ON_POLYLINE = 3 + + origin: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + destination: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_waypoint.Waypoint, + ) + intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=gmr_waypoint.Waypoint, + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=4, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=5, + enum=gmr_routing_preference.RoutingPreference, + ) + polyline_quality: polyline.PolylineQuality = proto.Field( + proto.ENUM, + number=6, + enum=polyline.PolylineQuality, + ) + polyline_encoding: polyline.PolylineEncoding = proto.Field( + proto.ENUM, + number=12, + enum=polyline.PolylineEncoding, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + compute_alternative_routes: bool = proto.Field( + proto.BOOL, + number=8, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=9, + message=gmr_route_modifiers.RouteModifiers, + ) + language_code: str = proto.Field( + proto.STRING, + number=10, + ) + region_code: str = proto.Field( + proto.STRING, + number=16, + ) + units: gmr_units.Units = proto.Field( + proto.ENUM, + number=11, + enum=gmr_units.Units, + ) + requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( + proto.ENUM, + number=14, + enum=ReferenceRoute, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=15, + enum=ExtraComputation, + ) + + +class ComputeRoutesResponse(proto.Message): + r"""ComputeRoutes the response message. + + Attributes: + routes (MutableSequence[google.maps.routing_v2.types.Route]): + Contains an array of computed routes (up to three) when you + specify compute_alternatives_routes, and contains just one + route when you don't. When this array contains multiple + entries, the first one is the most recommended route. If the + array is empty, then it means no route could be found. + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route results with all of the input + preferences, it may fallback to using a + different way of computation. When fallback mode + is used, this field contains detailed info about + the fallback response. Otherwise this field is + unset. + geocoding_results (google.maps.routing_v2.types.GeocodingResults): + Contains geocoding response info for + waypoints specified as addresses. + """ + + routes: MutableSequence[route.Route] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=route.Route, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_fallback_info.FallbackInfo, + ) + geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_geocoding_results.GeocodingResults, + ) + + +class ComputeRouteMatrixRequest(proto.Message): + r"""ComputeRouteMatrix request message + + Attributes: + origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): + Required. Array of origins, which determines the rows of the + response matrix. Several size restrictions apply to the + cardinality of origins and destinations: + + - The number of elements (origins × destinations) must be + no greater than 625 in any case. + - The number of elements (origins × destinations) must be + no greater than 100 if routing_preference is set to + ``TRAFFIC_AWARE_OPTIMAL``. + - The number of waypoints (origins + destinations) + specified as ``place_id`` must be no greater than 50. + destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): + Required. Array of destinations, which + determines the columns of the response matrix. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + Optional. Specifies the mode of + transportation. + routing_preference (google.maps.routing_v2.types.RoutingPreference): + Optional. Specifies how to compute the route. The server + attempts to use the selected routing preference to compute + the route. If the routing preference results in an error or + an extra long latency, an error is returned. You can specify + this option only when the ``travel_mode`` is ``DRIVE`` or + ``TWO_WHEELER``, otherwise the request fails. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The departure time. If you don't + set this value, this defaults to the time that + you made the request. If you set this value to a + time that has already occurred, the request + fails. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + See `Language + Support `__ + for the list of supported languages. When you don't provide + this value, the display language is inferred from the + location of the first origin. + region_code (str): + Optional. The region code, specified as a ccTLD ("top-level + domain") two-character value. For more information see + https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains + extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): + Optional. A list of extra computations which + may be used to complete the request. Note: These + extra computations may return extra fields on + the response. These extra fields must also be + specified in the field mask to be returned in + the response. + """ + class ExtraComputation(proto.Enum): + r"""Extra computations to perform while completing the request. + + Values: + EXTRA_COMPUTATION_UNSPECIFIED (0): + Not used. Requests containing this value will + fail. + TOLLS (1): + Toll information for the matrix element(s). + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + + origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteMatrixOrigin', + ) + destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='RouteMatrixDestination', + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=3, + enum=route_travel_mode.RouteTravelMode, + ) + routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( + proto.ENUM, + number=4, + enum=gmr_routing_preference.RoutingPreference, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + region_code: str = proto.Field( + proto.STRING, + number=9, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=ExtraComputation, + ) + + +class RouteMatrixOrigin(proto.Message): + r"""A single origin for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Origin waypoint + route_modifiers (google.maps.routing_v2.types.RouteModifiers): + Optional. Modifiers for every route that + takes this as the origin + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_route_modifiers.RouteModifiers, + ) + + +class RouteMatrixDestination(proto.Message): + r"""A single destination for ComputeRouteMatrixRequest + + Attributes: + waypoint (google.maps.routing_v2.types.Waypoint): + Required. Destination waypoint + """ + + waypoint: gmr_waypoint.Waypoint = proto.Field( + proto.MESSAGE, + number=1, + message=gmr_waypoint.Waypoint, + ) + + +class RouteMatrixElement(proto.Message): + r"""Encapsulates route information computed for an + origin/destination pair in the ComputeRouteMatrix API. This + proto can be streamed to the client. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + origin_index (int): + Zero-based index of the origin in the + request. + + This field is a member of `oneof`_ ``_origin_index``. + destination_index (int): + Zero-based index of the destination in the + request. + + This field is a member of `oneof`_ ``_destination_index``. + status (google.rpc.status_pb2.Status): + Error status code for this element. + condition (google.maps.routing_v2.types.RouteMatrixElementCondition): + Indicates whether the route was found or not. + Independent of status. + distance_meters (int): + The travel distance of the route, in meters. + duration (google.protobuf.duration_pb2.Duration): + The length of time needed to navigate the route. If you set + the + [routing_preference][google.maps.routing.v2.ComputeRouteMatrixRequest.routing_preference] + to ``TRAFFIC_UNAWARE``, then this value is the same as + ``static_duration``. If you set the ``routing_preference`` + to either ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``, + then this value is calculated taking traffic conditions into + account. + static_duration (google.protobuf.duration_pb2.Duration): + The duration of traveling through the route + without taking traffic conditions into + consideration. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. For + example: restriction information and toll + information + fallback_info (google.maps.routing_v2.types.FallbackInfo): + In some cases when the server is not able to + compute the route with the given preferences for + this particular origin/destination pair, it may + fall back to using a different mode of + computation. When fallback mode is used, this + field contains detailed information about the + fallback response. Otherwise this field is + unset. + """ + + origin_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + destination_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + condition: 'RouteMatrixElementCondition' = proto.Field( + proto.ENUM, + number=9, + enum='RouteMatrixElementCondition', + ) + distance_meters: int = proto.Field( + proto.INT32, + number=4, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + static_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + travel_advisory: route.RouteTravelAdvisory = proto.Field( + proto.MESSAGE, + number=7, + message=route.RouteTravelAdvisory, + ) + fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( + proto.MESSAGE, + number=8, + message=gmr_fallback_info.FallbackInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py new file mode 100644 index 000000000000..d303b4947306 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'RoutingPreference', + }, +) + + +class RoutingPreference(proto.Enum): + r"""A set of values that specify factors to take into + consideration when calculating the route. + + Values: + ROUTING_PREFERENCE_UNSPECIFIED (0): + No routing preference specified. Default to + ``TRAFFIC_UNAWARE``. + TRAFFIC_UNAWARE (1): + Computes routes without taking live traffic conditions into + consideration. Suitable when traffic conditions don't matter + or are not applicable. Using this value produces the lowest + latency. Note: For + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] + ``DRIVE`` and ``TWO_WHEELER`` choice of route and duration + are based on road network and average time-independent + traffic conditions. Results for a given request may vary + over time due to changes in the road network, updated + average traffic conditions, and the distributed nature of + the service. Results may also vary between nearly-equivalent + routes at any time or frequency. + TRAFFIC_AWARE (2): + Calculates routes taking live traffic conditions into + consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, + some optimizations are applied to significantly reduce + latency. + TRAFFIC_AWARE_OPTIMAL (3): + Calculates the routes taking live traffic + conditions into consideration, without applying + most performance optimizations. Using this value + produces the highest latency. + """ + ROUTING_PREFERENCE_UNSPECIFIED = 0 + TRAFFIC_UNAWARE = 1 + TRAFFIC_AWARE = 2 + TRAFFIC_AWARE_OPTIMAL = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py new file mode 100644 index 000000000000..e68d9247b109 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'SpeedReadingInterval', + }, +) + + +class SpeedReadingInterval(proto.Message): + r"""Traffic density indicator on a contiguous segment of a polyline or + path. Given a path with points P_0, P_1, ... , P_N (zero-based + index), the SpeedReadingInterval defines an interval and describes + its traffic using the following categories. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_polyline_point_index (int): + The starting index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_start_polyline_point_index``. + end_polyline_point_index (int): + The ending index of this interval in the + polyline. + + This field is a member of `oneof`_ ``_end_polyline_point_index``. + speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): + Traffic speed in this interval. + + This field is a member of `oneof`_ ``speed_type``. + """ + class Speed(proto.Enum): + r"""The classification of polyline speed based on traffic data. + + Values: + SPEED_UNSPECIFIED (0): + Default value. This value is unused. + NORMAL (1): + Normal speed, no slowdown is detected. + SLOW (2): + Slowdown detected, but no traffic jam formed. + TRAFFIC_JAM (3): + Traffic jam detected. + """ + SPEED_UNSPECIFIED = 0 + NORMAL = 1 + SLOW = 2 + TRAFFIC_JAM = 3 + + start_polyline_point_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + end_polyline_point_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + speed: Speed = proto.Field( + proto.ENUM, + number=3, + oneof='speed_type', + enum=Speed, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py new file mode 100644 index 000000000000..1b7d73fd2f76 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.type import money_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TollInfo', + }, +) + + +class TollInfo(proto.Message): + r"""Encapsulates toll information on a + [Route][google.maps.routing.v2.Route] or on a + [RouteLeg][google.maps.routing.v2.RouteLeg]. + + Attributes: + estimated_price (MutableSequence[google.type.money_pb2.Money]): + The monetary amount of tolls for the corresponding + [Route][google.maps.routing.v2.Route] or + [RouteLeg][google.maps.routing.v2.RouteLeg]. This list + contains a money amount for each currency that is expected + to be charged by the toll stations. Typically this list will + contain only one item for routes with tolls in one currency. + For international trips, this list may contain multiple + items to reflect tolls in different currencies. + """ + + estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=money_pb2.Money, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py new file mode 100644 index 000000000000..0faa9d9865cf --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py @@ -0,0 +1,351 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TollPass', + }, +) + + +class TollPass(proto.Enum): + r"""List of toll passes around the world that we support. + + Values: + TOLL_PASS_UNSPECIFIED (0): + Not used. If this value is used, then the + request fails. + AU_ETOLL_TAG (82): + Sydney toll pass. See additional details at + https://www.myetoll.com.au. + AU_EWAY_TAG (83): + Sydney toll pass. See additional details at + https://www.tollpay.com.au. + AU_LINKT (2): + Australia-wide toll pass. + See additional details at + https://www.linkt.com.au/. + AR_TELEPASE (3): + Argentina toll pass. See additional details + at https://telepase.com.ar + BR_AUTO_EXPRESO (81): + Brazil toll pass. See additional details at + https://www.autoexpreso.com + BR_CONECTCAR (7): + Brazil toll pass. See additional details at + https://conectcar.com. + BR_MOVE_MAIS (8): + Brazil toll pass. See additional details at + https://movemais.com. + BR_PASSA_RAPIDO (88): + Brazil toll pass. See additional details at + https://pasorapido.gob.do/ + BR_SEM_PARAR (9): + Brazil toll pass. See additional details at + https://www.semparar.com.br. + BR_TAGGY (10): + Brazil toll pass. See additional details at + https://taggy.com.br. + BR_VELOE (11): + Brazil toll pass. See additional details at + https://veloe.com.br/site/onde-usar. + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): + Canada to United States border crossing. + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): + Canada to United States border crossing. + CA_US_BLUE_WATER_EDGE_PASS (18): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_CONNEXION (19): + Ontario, Canada to Michigan, United States + border crossing. + CA_US_NEXUS_CARD (20): + Canada to United States border crossing. + ID_E_TOLL (16): + Indonesia. + E-card provided by multiple banks used to pay + for tolls. All e-cards via banks are charged the + same so only one enum value is needed. E.g. - + Bank Mandiri + https://www.bankmandiri.co.id/e-money - BCA + https://www.bca.co.id/flazz + - BNI + https://www.bni.co.id/id-id/ebanking/tapcash + IN_FASTAG (78): + India. + IN_LOCAL_HP_PLATE_EXEMPT (79): + India, HP state plate exemption. + MX_IAVE (90): + Mexico toll pass. + https://iave.capufe.gob.mx/#/ + MX_PASE (91): + Mexico + https://www.pase.com.mx + MX_QUICKPASS (93): + Mexico + https://operadoravial.com/quick-pass/ + MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): + http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf + MX_TAG_IAVE (12): + Mexico + MX_TAG_TELEVIA (13): + Mexico toll pass company. One of many + operating in Mexico City. See additional details + at https://www.televia.com.mx. + MX_TELEVIA (92): + Mexico toll pass company. One of many + operating in Mexico City. + https://www.televia.com.mx + MX_VIAPASS (14): + Mexico toll pass. See additional details at + https://www.viapass.com.mx/viapass/web_home.aspx. + US_AL_FREEDOM_PASS (21): + AL, USA. + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): + AK, USA. + US_CA_FASTRAK (4): + CA, USA. + US_CA_FASTRAK_CAV_STICKER (86): + Indicates driver has any FasTrak pass in + addition to the DMV issued Clean Air Vehicle + (CAV) sticker. + https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml + US_CO_EXPRESSTOLL (23): + CO, USA. + US_CO_GO_PASS (24): + CO, USA. + US_DE_EZPASSDE (25): + DE, USA. + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): + FL, USA. + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): + FL, USA. + US_FL_EPASS (67): + FL, USA. + US_FL_GIBA_TOLL_PASS (68): + FL, USA. + US_FL_LEEWAY (69): + FL, USA. + US_FL_SUNPASS (70): + FL, USA. + US_FL_SUNPASS_PRO (71): + FL, USA. + US_IL_EZPASSIL (73): + IL, USA. + US_IL_IPASS (72): + IL, USA. + US_IN_EZPASSIN (26): + IN, USA. + US_KS_BESTPASS_HORIZON (27): + KS, USA. + US_KS_KTAG (28): + KS, USA. + US_KS_NATIONALPASS (29): + KS, USA. + US_KS_PREPASS_ELITEPASS (30): + KS, USA. + US_KY_RIVERLINK (31): + KY, USA. + US_LA_GEAUXPASS (32): + LA, USA. + US_LA_TOLL_TAG (33): + LA, USA. + US_MA_EZPASSMA (6): + MA, USA. + US_MD_EZPASSMD (34): + MD, USA. + US_ME_EZPASSME (35): + ME, USA. + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): + MI, USA. + US_MI_BCPASS (94): + MI, USA. + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): + MI, USA. + US_MI_IQ_PROX_CARD (38): + MI, USA. + US_MI_MACKINAC_BRIDGE_MAC_PASS (39): + MI, USA. + US_MI_NEXPRESS_TOLL (40): + MI, USA. + US_MN_EZPASSMN (41): + MN, USA. + US_NC_EZPASSNC (42): + NC, USA. + US_NC_PEACH_PASS (87): + NC, USA. + US_NC_QUICK_PASS (43): + NC, USA. + US_NH_EZPASSNH (80): + NH, USA. + US_NJ_DOWNBEACH_EXPRESS_PASS (75): + NJ, USA. + US_NJ_EZPASSNJ (74): + NJ, USA. + US_NY_EXPRESSPASS (76): + NY, USA. + US_NY_EZPASSNY (77): + NY, USA. + US_OH_EZPASSOH (44): + OH, USA. + US_PA_EZPASSPA (45): + PA, USA. + US_RI_EZPASSRI (46): + RI, USA. + US_SC_PALPASS (47): + SC, USA. + US_TX_BANCPASS (48): + TX, USA. + US_TX_DEL_RIO_PASS (49): + TX, USA. + US_TX_EFAST_PASS (50): + TX, USA. + US_TX_EAGLE_PASS_EXPRESS_CARD (51): + TX, USA. + US_TX_EPTOLL (52): + TX, USA. + US_TX_EZ_CROSS (53): + TX, USA. + US_TX_EZTAG (54): + TX, USA. + US_TX_LAREDO_TRADE_TAG (55): + TX, USA. + US_TX_PLUSPASS (56): + TX, USA. + US_TX_TOLLTAG (57): + TX, USA. + US_TX_TXTAG (58): + TX, USA. + US_TX_XPRESS_CARD (59): + TX, USA. + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): + UT, USA. + US_VA_EZPASSVA (61): + VA, USA. + US_WA_BREEZEBY (17): + WA, USA. + US_WA_GOOD_TO_GO (1): + WA, USA. + US_WV_EZPASSWV (62): + WV, USA. + US_WV_MEMORIAL_BRIDGE_TICKETS (63): + WV, USA. + US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): + WV, USA. + """ + TOLL_PASS_UNSPECIFIED = 0 + AU_ETOLL_TAG = 82 + AU_EWAY_TAG = 83 + AU_LINKT = 2 + AR_TELEPASE = 3 + BR_AUTO_EXPRESO = 81 + BR_CONECTCAR = 7 + BR_MOVE_MAIS = 8 + BR_PASSA_RAPIDO = 88 + BR_SEM_PARAR = 9 + BR_TAGGY = 10 + BR_VELOE = 11 + CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 + CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 + CA_US_BLUE_WATER_EDGE_PASS = 18 + CA_US_CONNEXION = 19 + CA_US_NEXUS_CARD = 20 + ID_E_TOLL = 16 + IN_FASTAG = 78 + IN_LOCAL_HP_PLATE_EXEMPT = 79 + MX_IAVE = 90 + MX_PASE = 91 + MX_QUICKPASS = 93 + MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 + MX_TAG_IAVE = 12 + MX_TAG_TELEVIA = 13 + MX_TELEVIA = 92 + MX_VIAPASS = 14 + US_AL_FREEDOM_PASS = 21 + US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 + US_CA_FASTRAK = 4 + US_CA_FASTRAK_CAV_STICKER = 86 + US_CO_EXPRESSTOLL = 23 + US_CO_GO_PASS = 24 + US_DE_EZPASSDE = 25 + US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 + US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 + US_FL_EPASS = 67 + US_FL_GIBA_TOLL_PASS = 68 + US_FL_LEEWAY = 69 + US_FL_SUNPASS = 70 + US_FL_SUNPASS_PRO = 71 + US_IL_EZPASSIL = 73 + US_IL_IPASS = 72 + US_IN_EZPASSIN = 26 + US_KS_BESTPASS_HORIZON = 27 + US_KS_KTAG = 28 + US_KS_NATIONALPASS = 29 + US_KS_PREPASS_ELITEPASS = 30 + US_KY_RIVERLINK = 31 + US_LA_GEAUXPASS = 32 + US_LA_TOLL_TAG = 33 + US_MA_EZPASSMA = 6 + US_MD_EZPASSMD = 34 + US_ME_EZPASSME = 35 + US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 + US_MI_BCPASS = 94 + US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 + US_MI_IQ_PROX_CARD = 38 + US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 + US_MI_NEXPRESS_TOLL = 40 + US_MN_EZPASSMN = 41 + US_NC_EZPASSNC = 42 + US_NC_PEACH_PASS = 87 + US_NC_QUICK_PASS = 43 + US_NH_EZPASSNH = 80 + US_NJ_DOWNBEACH_EXPRESS_PASS = 75 + US_NJ_EZPASSNJ = 74 + US_NY_EXPRESSPASS = 76 + US_NY_EZPASSNY = 77 + US_OH_EZPASSOH = 44 + US_PA_EZPASSPA = 45 + US_RI_EZPASSRI = 46 + US_SC_PALPASS = 47 + US_TX_BANCPASS = 48 + US_TX_DEL_RIO_PASS = 49 + US_TX_EFAST_PASS = 50 + US_TX_EAGLE_PASS_EXPRESS_CARD = 51 + US_TX_EPTOLL = 52 + US_TX_EZ_CROSS = 53 + US_TX_EZTAG = 54 + US_TX_LAREDO_TRADE_TAG = 55 + US_TX_PLUSPASS = 56 + US_TX_TOLLTAG = 57 + US_TX_TXTAG = 58 + US_TX_XPRESS_CARD = 59 + US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 + US_VA_EZPASSVA = 61 + US_WA_BREEZEBY = 17 + US_WA_GOOD_TO_GO = 1 + US_WV_EZPASSWV = 62 + US_WV_MEMORIAL_BRIDGE_TICKETS = 63 + US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py new file mode 100644 index 000000000000..93cfaf1ee04c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Units', + }, +) + + +class Units(proto.Enum): + r"""A set of values that specify the unit of measure used in the + display. + + Values: + UNITS_UNSPECIFIED (0): + Units of measure not specified. Defaults to + the unit of measure inferred from the request. + METRIC (1): + Metric units of measure. + IMPERIAL (2): + Imperial (English) units of measure. + """ + UNITS_UNSPECIFIED = 0 + METRIC = 1 + IMPERIAL = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py new file mode 100644 index 000000000000..faa6b5957eb3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'VehicleEmissionType', + }, +) + + +class VehicleEmissionType(proto.Enum): + r"""A set of values describing the vehicle's emission type. Applies only + to the ``DRIVE`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + + Values: + VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): + No emission type specified. Default to ``GASOLINE``. + GASOLINE (1): + Gasoline/petrol fueled vehicle. + ELECTRIC (2): + Electricity powered vehicle. + HYBRID (3): + Hybrid fuel (such as gasoline + electric) + vehicle. + DIESEL (4): + Diesel fueled vehicle. + """ + VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 + GASOLINE = 1 + ELECTRIC = 2 + HYBRID = 3 + DIESEL = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py new file mode 100644 index 000000000000..a2ad1ffd949e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import vehicle_emission_type + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'VehicleInfo', + }, +) + + +class VehicleInfo(proto.Message): + r"""Encapsulates the vehicle information, such as the license + plate last character. + + Attributes: + emission_type (google.maps.routing_v2.types.VehicleEmissionType): + Describes the vehicle's emission type. Applies only to the + ``DRIVE`` travel mode. + """ + + emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( + proto.ENUM, + number=2, + enum=vehicle_emission_type.VehicleEmissionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py new file mode 100644 index 000000000000..71ae89e0e84f --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.routing_v2.types import location as gmr_location + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Waypoint', + }, +) + + +class Waypoint(proto.Message): + r"""Encapsulates a waypoint. Waypoints mark both the beginning + and end of a route, and include intermediate stops along the + route. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location (google.maps.routing_v2.types.Location): + A point specified using geographic + coordinates, including an optional heading. + + This field is a member of `oneof`_ ``location_type``. + place_id (str): + The POI Place ID associated with the + waypoint. + + This field is a member of `oneof`_ ``location_type``. + address (str): + Human readable address or a plus code. + See https://plus.codes for details. + + This field is a member of `oneof`_ ``location_type``. + via (bool): + Marks this waypoint as a milestone rather a stopping point. + For each non-via waypoint in the request, the response + appends an entry to the + [legs][google.maps.routing.v2.Route.legs] array to provide + the details for stopovers on that leg of the trip. Set this + value to true when you want the route to pass through this + waypoint without stopping over. Via waypoints don't cause an + entry to be added to the ``legs`` array, but they do route + the journey through the waypoint. You can only set this + value on waypoints that are intermediates. The request fails + if you set this field on terminal waypoints. If + ``ComputeRoutesRequest.optimize_waypoint_order`` is set to + true then this field cannot be set to true; otherwise, the + request fails. + vehicle_stopover (bool): + Indicates that the waypoint is meant for vehicles to stop + at, where the intention is to either pickup or drop-off. + When you set this value, the calculated route won't include + non-\ ``via`` waypoints on roads that are unsuitable for + pickup and drop-off. This option works only for ``DRIVE`` + and ``TWO_WHEELER`` travel modes, and when the + ``location_type`` is + [Location][google.maps.routing.v2.Location]. + side_of_road (bool): + Indicates that the location of this waypoint is meant to + have a preference for the vehicle to stop at a particular + side of road. When you set this value, the route will pass + through the location so that the vehicle can stop at the + side of road that the location is biased towards from the + center of the road. This option works only for 'DRIVE' and + 'TWO_WHEELER' + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + """ + + location: gmr_location.Location = proto.Field( + proto.MESSAGE, + number=1, + oneof='location_type', + message=gmr_location.Location, + ) + place_id: str = proto.Field( + proto.STRING, + number=2, + oneof='location_type', + ) + address: str = proto.Field( + proto.STRING, + number=7, + oneof='location_type', + ) + via: bool = proto.Field( + proto.BOOL, + number=3, + ) + vehicle_stopover: bool = proto.Field( + proto.BOOL, + number=4, + ) + side_of_road: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py new file mode 100644 index 000000000000..59757e684c85 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/maps/routing_v2/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py new file mode 100644 index 000000000000..381f53f7a26e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +async def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = await client.compute_route_matrix(request=request) + + # Handle the response + async for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py new file mode 100644 index 000000000000..125691404b0b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRouteMatrix +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRouteMatrix_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +def sample_compute_route_matrix(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRouteMatrixRequest( + ) + + # Make the request + stream = client.compute_route_matrix(request=request) + + # Handle the response + for response in stream: + print(response) + +# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py new file mode 100644 index 000000000000..c978c3e55cd7 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +async def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesAsyncClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = await client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py new file mode 100644 index 000000000000..ca13730e4ddc --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeRoutes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routing + + +# [START routes_v2_generated_Routes_ComputeRoutes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routing_v2 + + +def sample_compute_routes(): + # Create a client + client = routing_v2.RoutesClient() + + # Initialize request argument(s) + request = routing_v2.ComputeRoutesRequest( + ) + + # Make the request + response = client.compute_routes(request=request) + + # Handle the response + print(response) + +# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json new file mode 100644 index 000000000000..b5ed5aca319c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json @@ -0,0 +1,321 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.routing.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-maps-routing", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_route_matrix_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRouteMatrix" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", + "shortName": "compute_route_matrix" + }, + "description": "Sample for ComputeRouteMatrix", + "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_route_matrix_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routing_v2.RoutesAsyncClient", + "shortName": "RoutesAsyncClient" + }, + "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routing_v2.RoutesClient", + "shortName": "RoutesClient" + }, + "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", + "method": { + "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", + "service": { + "fullName": "google.maps.routing.v2.Routes", + "shortName": "Routes" + }, + "shortName": "ComputeRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routing_v2.types.ComputeRoutesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", + "shortName": "compute_routes" + }, + "description": "Sample for ComputeRoutes", + "file": "routes_v2_generated_routes_compute_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routes_v2_generated_Routes_ComputeRoutes_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routes_v2_generated_routes_compute_routes_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py new file mode 100644 index 000000000000..ab8c9f6352a2 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class routingCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'language_code', 'region_code', 'extra_computations', ), + 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'region_code', 'units', 'requested_reference_routes', 'extra_computations', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=routingCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the routing client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py new file mode 100644 index 000000000000..b93d9d947fd8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-maps-routing' + + +description = "Google Maps Routing API client library" + +version = {} +with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "google-geo-type >= 0.1.0, <1.0.0dev", +] +url = "https://github.com/googleapis/python-maps-routing" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.maps"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt new file mode 100644 index 000000000000..33ac865954a6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 +google-geo-type==0.1.0 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py new file mode 100644 index 000000000000..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py new file mode 100644 index 000000000000..55f7b3a4ba31 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py @@ -0,0 +1,1750 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.maps.routing_v2.services.routes import RoutesAsyncClient +from google.maps.routing_v2.services.routes import RoutesClient +from google.maps.routing_v2.services.routes import transports +from google.maps.routing_v2.types import fallback_info +from google.maps.routing_v2.types import geocoding_results +from google.maps.routing_v2.types import location +from google.maps.routing_v2.types import polyline +from google.maps.routing_v2.types import route +from google.maps.routing_v2.types import route_modifiers +from google.maps.routing_v2.types import route_travel_mode +from google.maps.routing_v2.types import routes_service +from google.maps.routing_v2.types import routing_preference +from google.maps.routing_v2.types import toll_passes +from google.maps.routing_v2.types import units +from google.maps.routing_v2.types import vehicle_emission_type +from google.maps.routing_v2.types import vehicle_info +from google.maps.routing_v2.types import waypoint +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +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 RoutesClient._get_default_mtls_endpoint(None) is None + assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RoutesGrpcTransport, "grpc"), + (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RoutesRestTransport, "rest"), +]) +def test_routes_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RoutesClient, "grpc"), + (RoutesAsyncClient, "grpc_asyncio"), + (RoutesClient, "rest"), +]) +def test_routes_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://routes.googleapis.com' + ) + + +def test_routes_client_get_transport_class(): + transport = RoutesClient.get_transport_class() + available_transports = [ + transports.RoutesGrpcTransport, + transports.RoutesRestTransport, + ] + assert transport in available_transports + + transport = RoutesClient.get_transport_class("grpc") + assert transport == transports.RoutesGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +def test_routes_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RoutesClient, transports.RoutesRestTransport, "rest", "true"), + (RoutesClient, transports.RoutesRestTransport, "rest", "false"), +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_routes_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + RoutesClient, RoutesAsyncClient +]) +@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) +def test_routes_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc"), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), + (RoutesClient, transports.RoutesRestTransport, "rest"), +]) +def test_routes_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + 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, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RoutesClient, transports.RoutesRestTransport, "rest", None), +]) +def test_routes_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_routes_client_client_options_from_dict(): + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RoutesClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_routes_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "routes.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( +), + scopes=None, + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes(request_type, transport: str = 'grpc'): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = routes_service.ComputeRoutesResponse( + ) + response = client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + client.compute_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + +@pytest.mark.asyncio +async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( + )) + response = await client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +@pytest.mark.asyncio +async def test_compute_routes_async_from_dict(): + await test_compute_routes_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix(request_type, transport: str = 'grpc'): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iter([routes_service.RouteMatrixElement()]) + response = client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, routes_service.RouteMatrixElement) + + +def test_compute_route_matrix_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + client.compute_route_matrix() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + +@pytest.mark.asyncio +async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) + response = await client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest() + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, routes_service.RouteMatrixElement) + + +@pytest.mark.asyncio +async def test_compute_route_matrix_async_from_dict(): + await test_compute_route_matrix_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes_rest(request_type): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = routes_service.ComputeRoutesResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.compute_routes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): + transport_class = transports.RoutesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.ComputeRoutesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.compute_routes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_routes_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_routes._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_routes_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) + + request = routes_service.ComputeRoutesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.ComputeRoutesResponse() + + client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_routes_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRoutesRequest): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.compute_routes(request) + + +def test_compute_routes_rest_error(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix_rest(request_type): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = routes_service.RouteMatrixElement( + origin_index=1279, + destination_index=1817, + condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, + distance_meters=1594, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.compute_route_matrix(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.RouteMatrixElement) + assert response.origin_index == 1279 + assert response.destination_index == 1817 + assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS + assert response.distance_meters == 1594 + + +def test_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): + transport_class = transports.RoutesRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = routes_service.RouteMatrixElement() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + with mock.patch.object(response_value, 'iter_content') as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.compute_route_matrix(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_compute_route_matrix_rest_unset_required_fields(): + transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_route_matrix_rest_interceptors(null_interceptor): + transport = transports.RoutesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), + ) + client = RoutesClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ + mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) + req.return_value._content = "[{}]".format(req.return_value._content) + + request = routes_service.ComputeRouteMatrixRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = routes_service.RouteMatrixElement() + + client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_compute_route_matrix_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.compute_route_matrix(request) + + +def test_compute_route_matrix_rest_error(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutesClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutesClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutesClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RoutesClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutesGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RoutesGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = RoutesClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RoutesGrpcTransport, + ) + +def test_routes_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_routes_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RoutesTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'compute_routes', + 'compute_route_matrix', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_routes_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( +), + quota_project_id="octopus", + ) + + +def test_routes_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RoutesTransport() + adc.assert_called_once() + + +def test_routes_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RoutesClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + ], +) +def test_routes_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=(), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutesGrpcTransport, + transports.RoutesGrpcAsyncIOTransport, + transports.RoutesRestTransport, + ], +) +def test_routes_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RoutesGrpcTransport, grpc_helpers), + (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_routes_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "routes.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( +), + scopes=["1", "2"], + default_host="routes.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_routes_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.RoutesRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_routes_host_no_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_routes_host_with_port(transport_name): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'routes.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://routes.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_routes_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RoutesClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RoutesClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.compute_routes._session + session2 = client2.transport.compute_routes._session + assert session1 != session2 + session1 = client1.transport.compute_route_matrix._session + session2 = client2.transport.compute_route_matrix._session + assert session1 != session2 +def test_routes_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_routes_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RoutesGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + 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 + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + 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=cred, + credentials_file=None, + scopes=None, + 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 + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) +def test_routes_transport_channel_mtls_with_adc( + transport_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), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + 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 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RoutesClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RoutesClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = RoutesClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RoutesClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RoutesClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RoutesClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = RoutesClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RoutesClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RoutesClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RoutesClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RoutesClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: + transport_class = RoutesClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RoutesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (RoutesClient, transports.RoutesGrpcTransport), + (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From 5f245e19991d5eda4b13a62495293d30722c1c99 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 22 Mar 2023 00:53:13 +0000 Subject: [PATCH 10/12] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../google-maps-routing/v2/.coveragerc | 13 - .../google-maps-routing/v2/.flake8 | 33 - .../google-maps-routing/v2/MANIFEST.in | 2 - .../google-maps-routing/v2/README.rst | 49 - .../google-maps-routing/v2/docs/conf.py | 376 ---- .../google-maps-routing/v2/docs/index.rst | 7 - .../v2/docs/routing_v2/routes.rst | 6 - .../v2/docs/routing_v2/services.rst | 6 - .../v2/docs/routing_v2/types.rst | 6 - .../v2/google/maps/routing/__init__.py | 97 - .../v2/google/maps/routing/gapic_version.py | 16 - .../v2/google/maps/routing/py.typed | 2 - .../v2/google/maps/routing_v2/__init__.py | 98 - .../maps/routing_v2/gapic_metadata.json | 58 - .../google/maps/routing_v2/gapic_version.py | 16 - .../v2/google/maps/routing_v2/py.typed | 2 - .../maps/routing_v2/services/__init__.py | 15 - .../routing_v2/services/routes/__init__.py | 22 - .../services/routes/async_client.py | 416 ---- .../maps/routing_v2/services/routes/client.py | 613 ------ .../services/routes/transports/__init__.py | 38 - .../services/routes/transports/base.py | 161 -- .../services/routes/transports/grpc.py | 363 ---- .../routes/transports/grpc_asyncio.py | 362 ---- .../services/routes/transports/rest.py | 417 ---- .../google/maps/routing_v2/types/__init__.py | 105 - .../maps/routing_v2/types/fallback_info.py | 105 - .../routing_v2/types/geocoding_results.py | 127 -- .../google/maps/routing_v2/types/location.py | 63 - .../google/maps/routing_v2/types/maneuver.py | 96 - .../types/navigation_instruction.py | 58 - .../google/maps/routing_v2/types/polyline.py | 113 -- .../v2/google/maps/routing_v2/types/route.py | 411 ---- .../maps/routing_v2/types/route_label.py | 58 - .../maps/routing_v2/types/route_modifiers.py | 98 - .../routing_v2/types/route_travel_mode.py | 59 - .../maps/routing_v2/types/routes_service.py | 544 ----- .../routing_v2/types/routing_preference.py | 69 - .../types/speed_reading_interval.py | 92 - .../google/maps/routing_v2/types/toll_info.py | 57 - .../maps/routing_v2/types/toll_passes.py | 351 ---- .../v2/google/maps/routing_v2/types/units.py | 49 - .../routing_v2/types/vehicle_emission_type.py | 56 - .../maps/routing_v2/types/vehicle_info.py | 50 - .../google/maps/routing_v2/types/waypoint.py | 126 -- .../google-maps-routing/v2/mypy.ini | 3 - .../google-maps-routing/v2/noxfile.py | 184 -- ...rated_routes_compute_route_matrix_async.py | 52 - ...erated_routes_compute_route_matrix_sync.py | 52 - ...2_generated_routes_compute_routes_async.py | 51 - ...v2_generated_routes_compute_routes_sync.py | 51 - ...ippet_metadata_google.maps.routing.v2.json | 321 --- .../v2/scripts/fixup_routing_v2_keywords.py | 177 -- .../google-maps-routing/v2/setup.py | 91 - .../v2/testing/constraints-3.10.txt | 7 - .../v2/testing/constraints-3.11.txt | 7 - .../v2/testing/constraints-3.12.txt | 7 - .../v2/testing/constraints-3.7.txt | 10 - .../v2/testing/constraints-3.8.txt | 7 - .../v2/testing/constraints-3.9.txt | 7 - .../google-maps-routing/v2/tests/__init__.py | 16 - .../v2/tests/unit/__init__.py | 16 - .../v2/tests/unit/gapic/__init__.py | 16 - .../tests/unit/gapic/routing_v2/__init__.py | 16 - .../unit/gapic/routing_v2/test_routes.py | 1750 ----------------- .../maps/routing_v2/types/fallback_info.py | 8 +- .../routing_v2/types/geocoding_results.py | 6 +- .../google/maps/routing_v2/types/location.py | 3 +- .../google/maps/routing_v2/types/route.py | 12 +- .../maps/routing_v2/types/route_label.py | 9 +- .../maps/routing_v2/types/route_modifiers.py | 13 +- .../routing_v2/types/route_travel_mode.py | 10 +- .../maps/routing_v2/types/routes_service.py | 25 +- .../routing_v2/types/routing_preference.py | 16 +- .../types/speed_reading_interval.py | 3 + .../google/maps/routing_v2/types/toll_info.py | 21 +- .../maps/routing_v2/types/toll_passes.py | 3 + .../routing_v2/types/vehicle_emission_type.py | 8 +- .../maps/routing_v2/types/vehicle_info.py | 4 +- .../google/maps/routing_v2/types/waypoint.py | 11 +- 80 files changed, 88 insertions(+), 8786 deletions(-) delete mode 100644 owl-bot-staging/google-maps-routing/v2/.coveragerc delete mode 100644 owl-bot-staging/google-maps-routing/v2/.flake8 delete mode 100644 owl-bot-staging/google-maps-routing/v2/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-routing/v2/README.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/mypy.ini delete mode 100644 owl-bot-staging/google-maps-routing/v2/noxfile.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json delete mode 100644 owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/setup.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py diff --git a/owl-bot-staging/google-maps-routing/v2/.coveragerc b/owl-bot-staging/google-maps-routing/v2/.coveragerc deleted file mode 100644 index d0ce5597b0a9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/routing/__init__.py - google/maps/routing/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-maps-routing/v2/.flake8 b/owl-bot-staging/google-maps-routing/v2/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/.flake8 +++ /dev/null @@ -1,33 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in b/owl-bot-staging/google-maps-routing/v2/MANIFEST.in deleted file mode 100644 index c5b56c111c00..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/routing *.py -recursive-include google/maps/routing_v2 *.py diff --git a/owl-bot-staging/google-maps-routing/v2/README.rst b/owl-bot-staging/google-maps-routing/v2/README.rst deleted file mode 100644 index f0002366e552..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Routing API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Maps Routing API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-maps-routing/v2/docs/conf.py b/owl-bot-staging/google-maps-routing/v2/docs/conf.py deleted file mode 100644 index d7a10abed96b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-maps-routing documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -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"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-maps-routing" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# 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"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# 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 - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -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 = { - "description": "Google Maps Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# 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 - -# 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 - -# 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, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# 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 = [] - -# 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' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is 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 = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# 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' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# 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' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-maps-routing-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- 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', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-maps-routing.tex", - u"google-maps-routing 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 - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# 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 = [ - ( - root_doc, - "google-maps-routing", - u"Google Maps Routing Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-maps-routing", - u"google-maps-routing Documentation", - author, - "google-maps-routing", - "GAPIC library for Google Maps Routing API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# 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), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-maps-routing/v2/docs/index.rst b/owl-bot-staging/google-maps-routing/v2/docs/index.rst deleted file mode 100644 index e2563dd88ee9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - routing_v2/services - routing_v2/types diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst deleted file mode 100644 index 3d52309cddae..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/routes.rst +++ /dev/null @@ -1,6 +0,0 @@ -Routes ------------------------- - -.. automodule:: google.maps.routing_v2.services.routes - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst deleted file mode 100644 index e96568dc434c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Routing v2 API -======================================= -.. toctree:: - :maxdepth: 2 - - routes diff --git a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst b/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst deleted file mode 100644 index 176a5a812cf8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/routing_v2/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Routing v2 API -==================================== - -.. automodule:: google.maps.routing_v2.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py deleted file mode 100644 index 59020a3484c3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.maps.routing import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.routing_v2.services.routes.client import RoutesClient -from google.maps.routing_v2.services.routes.async_client import RoutesAsyncClient - -from google.maps.routing_v2.types.fallback_info import FallbackInfo -from google.maps.routing_v2.types.fallback_info import FallbackReason -from google.maps.routing_v2.types.fallback_info import FallbackRoutingMode -from google.maps.routing_v2.types.geocoding_results import GeocodedWaypoint -from google.maps.routing_v2.types.geocoding_results import GeocodingResults -from google.maps.routing_v2.types.location import Location -from google.maps.routing_v2.types.maneuver import Maneuver -from google.maps.routing_v2.types.navigation_instruction import NavigationInstruction -from google.maps.routing_v2.types.polyline import Polyline -from google.maps.routing_v2.types.polyline import PolylineEncoding -from google.maps.routing_v2.types.polyline import PolylineQuality -from google.maps.routing_v2.types.route import Route -from google.maps.routing_v2.types.route import RouteLeg -from google.maps.routing_v2.types.route import RouteLegStep -from google.maps.routing_v2.types.route import RouteLegStepTravelAdvisory -from google.maps.routing_v2.types.route import RouteLegTravelAdvisory -from google.maps.routing_v2.types.route import RouteTravelAdvisory -from google.maps.routing_v2.types.route_label import RouteLabel -from google.maps.routing_v2.types.route_modifiers import RouteModifiers -from google.maps.routing_v2.types.route_travel_mode import RouteTravelMode -from google.maps.routing_v2.types.routes_service import ComputeRouteMatrixRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesRequest -from google.maps.routing_v2.types.routes_service import ComputeRoutesResponse -from google.maps.routing_v2.types.routes_service import RouteMatrixDestination -from google.maps.routing_v2.types.routes_service import RouteMatrixElement -from google.maps.routing_v2.types.routes_service import RouteMatrixOrigin -from google.maps.routing_v2.types.routes_service import RouteMatrixElementCondition -from google.maps.routing_v2.types.routing_preference import RoutingPreference -from google.maps.routing_v2.types.speed_reading_interval import SpeedReadingInterval -from google.maps.routing_v2.types.toll_info import TollInfo -from google.maps.routing_v2.types.toll_passes import TollPass -from google.maps.routing_v2.types.units import Units -from google.maps.routing_v2.types.vehicle_emission_type import VehicleEmissionType -from google.maps.routing_v2.types.vehicle_info import VehicleInfo -from google.maps.routing_v2.types.waypoint import Waypoint - -__all__ = ('RoutesClient', - 'RoutesAsyncClient', - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py deleted file mode 100644 index 405b1cebcf15..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py deleted file mode 100644 index cd9d694f63c6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.maps.routing_v2 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.routes import RoutesClient -from .services.routes import RoutesAsyncClient - -from .types.fallback_info import FallbackInfo -from .types.fallback_info import FallbackReason -from .types.fallback_info import FallbackRoutingMode -from .types.geocoding_results import GeocodedWaypoint -from .types.geocoding_results import GeocodingResults -from .types.location import Location -from .types.maneuver import Maneuver -from .types.navigation_instruction import NavigationInstruction -from .types.polyline import Polyline -from .types.polyline import PolylineEncoding -from .types.polyline import PolylineQuality -from .types.route import Route -from .types.route import RouteLeg -from .types.route import RouteLegStep -from .types.route import RouteLegStepTravelAdvisory -from .types.route import RouteLegTravelAdvisory -from .types.route import RouteTravelAdvisory -from .types.route_label import RouteLabel -from .types.route_modifiers import RouteModifiers -from .types.route_travel_mode import RouteTravelMode -from .types.routes_service import ComputeRouteMatrixRequest -from .types.routes_service import ComputeRoutesRequest -from .types.routes_service import ComputeRoutesResponse -from .types.routes_service import RouteMatrixDestination -from .types.routes_service import RouteMatrixElement -from .types.routes_service import RouteMatrixOrigin -from .types.routes_service import RouteMatrixElementCondition -from .types.routing_preference import RoutingPreference -from .types.speed_reading_interval import SpeedReadingInterval -from .types.toll_info import TollInfo -from .types.toll_passes import TollPass -from .types.units import Units -from .types.vehicle_emission_type import VehicleEmissionType -from .types.vehicle_info import VehicleInfo -from .types.waypoint import Waypoint - -__all__ = ( - 'RoutesAsyncClient', -'ComputeRouteMatrixRequest', -'ComputeRoutesRequest', -'ComputeRoutesResponse', -'FallbackInfo', -'FallbackReason', -'FallbackRoutingMode', -'GeocodedWaypoint', -'GeocodingResults', -'Location', -'Maneuver', -'NavigationInstruction', -'Polyline', -'PolylineEncoding', -'PolylineQuality', -'Route', -'RouteLabel', -'RouteLeg', -'RouteLegStep', -'RouteLegStepTravelAdvisory', -'RouteLegTravelAdvisory', -'RouteMatrixDestination', -'RouteMatrixElement', -'RouteMatrixElementCondition', -'RouteMatrixOrigin', -'RouteModifiers', -'RouteTravelAdvisory', -'RouteTravelMode', -'RoutesClient', -'RoutingPreference', -'SpeedReadingInterval', -'TollInfo', -'TollPass', -'Units', -'VehicleEmissionType', -'VehicleInfo', -'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json deleted file mode 100644 index 8382cea1d39a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_metadata.json +++ /dev/null @@ -1,58 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.routing_v2", - "protoPackage": "google.maps.routing.v2", - "schema": "1.0", - "services": { - "Routes": { - "clients": { - "grpc": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RoutesAsyncClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - }, - "rest": { - "libraryClient": "RoutesClient", - "rpcs": { - "ComputeRouteMatrix": { - "methods": [ - "compute_route_matrix" - ] - }, - "ComputeRoutes": { - "methods": [ - "compute_routes" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py deleted file mode 100644 index 405b1cebcf15..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed deleted file mode 100644 index d62a4b821347..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-routing package uses inline types. diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py deleted file mode 100644 index e8e1c3845db5..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py deleted file mode 100644 index ff3f8f71863f..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import RoutesClient -from .async_client import RoutesAsyncClient - -__all__ = ( - 'RoutesClient', - 'RoutesAsyncClient', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py deleted file mode 100644 index 7f8df74a140b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, AsyncIterable, Awaitable, Sequence, Tuple, Type, Union - -from google.maps.routing_v2 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .client import RoutesClient - - -class RoutesAsyncClient: - """The Routes API.""" - - _client: RoutesClient - - DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(RoutesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RoutesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RoutesClient.common_folder_path) - parse_common_folder_path = staticmethod(RoutesClient.parse_common_folder_path) - common_organization_path = staticmethod(RoutesClient.common_organization_path) - parse_common_organization_path = staticmethod(RoutesClient.parse_common_organization_path) - common_project_path = staticmethod(RoutesClient.common_project_path) - parse_common_project_path = staticmethod(RoutesClient.parse_common_project_path) - common_location_path = staticmethod(RoutesClient.common_location_path) - parse_common_location_path = staticmethod(RoutesClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_info.__func__(RoutesAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesAsyncClient: The constructed client. - """ - return RoutesClient.from_service_account_file.__func__(RoutesAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return RoutesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(RoutesClient).get_transport_class, type(RoutesClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, RoutesTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.RoutesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RoutesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]]): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # Create or coerce a protobuf request object. - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.compute_routes, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[routes_service.RouteMatrixElement]]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - - Args: - request (Optional[Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]]): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - AsyncIterable[google.maps.routing_v2.types.RouteMatrixElement]: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - # Create or coerce a protobuf request object. - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.compute_route_matrix, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RoutesAsyncClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py deleted file mode 100644 index 1943383c7246..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py +++ /dev/null @@ -1,613 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast - -from google.maps.routing_v2 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import routes_service -from google.protobuf import duration_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import RoutesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RoutesGrpcTransport -from .transports.grpc_asyncio import RoutesGrpcAsyncIOTransport -from .transports.rest import RoutesRestTransport - - -class RoutesClientMeta(type): - """Metaclass for the Routes client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] - _transport_registry["grpc"] = RoutesGrpcTransport - _transport_registry["grpc_asyncio"] = RoutesGrpcAsyncIOTransport - _transport_registry["rest"] = RoutesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RoutesTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class RoutesClient(metaclass=RoutesClientMeta): - """The Routes API.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "routes.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RoutesClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> RoutesTransport: - """Returns the transport used by the client instance. - - Returns: - RoutesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RoutesTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, RoutesTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, RoutesTransport): - # transport is a RoutesTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def compute_routes(self, - request: Optional[Union[routes_service.ComputeRoutesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> routes_service.ComputeRoutesResponse: - r"""Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRoutesRequest, dict]): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.routing_v2.types.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a routes_service.ComputeRoutesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, routes_service.ComputeRoutesRequest): - request = routes_service.ComputeRoutesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_routes] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def compute_route_matrix(self, - request: Optional[Union[routes_service.ComputeRouteMatrixRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[routes_service.RouteMatrixElement]: - r"""Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import routing_v2 - - def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - - Args: - request (Union[google.maps.routing_v2.types.ComputeRouteMatrixRequest, dict]): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - Iterable[google.maps.routing_v2.types.RouteMatrixElement]: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a routes_service.ComputeRouteMatrixRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, routes_service.ComputeRouteMatrixRequest): - request = routes_service.ComputeRouteMatrixRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.compute_route_matrix] - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "RoutesClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RoutesClient", -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py deleted file mode 100644 index a15967f001c9..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import RoutesTransport -from .grpc import RoutesGrpcTransport -from .grpc_asyncio import RoutesGrpcAsyncIOTransport -from .rest import RoutesRestTransport -from .rest import RoutesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RoutesTransport]] -_transport_registry['grpc'] = RoutesGrpcTransport -_transport_registry['grpc_asyncio'] = RoutesGrpcAsyncIOTransport -_transport_registry['rest'] = RoutesRestTransport - -__all__ = ( - 'RoutesTransport', - 'RoutesGrpcTransport', - 'RoutesGrpcAsyncIOTransport', - 'RoutesRestTransport', - 'RoutesRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py deleted file mode 100644 index a6fa68993eca..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py +++ /dev/null @@ -1,161 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.maps.routing_v2 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.maps.routing_v2.types import routes_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class RoutesTransport(abc.ABC): - """Abstract transport class for Routes.""" - - AUTH_SCOPES = ( - ) - - DEFAULT_HOST: str = 'routes.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.compute_routes: gapic_v1.method.wrap_method( - self.compute_routes, - default_timeout=None, - client_info=client_info, - ), - self.compute_route_matrix: gapic_v1.method.wrap_method( - self.compute_route_matrix, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Union[ - routes_service.ComputeRoutesResponse, - Awaitable[routes_service.ComputeRoutesResponse] - ]]: - raise NotImplementedError() - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Union[ - routes_service.RouteMatrixElement, - Awaitable[routes_service.RouteMatrixElement] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RoutesTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py deleted file mode 100644 index 8316c8b03587..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py +++ /dev/null @@ -1,363 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO - - -class RoutesGrpcTransport(RoutesTransport): - """gRPC backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - ~.ComputeRoutesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self.grpc_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - ~.RouteMatrixElement]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RoutesGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py deleted file mode 100644 index 752c5eaefc33..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py +++ /dev/null @@ -1,362 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.maps.routing_v2.types import routes_service -from .base import RoutesTransport, DEFAULT_CLIENT_INFO -from .grpc import RoutesGrpcTransport - - -class RoutesGrpcAsyncIOTransport(RoutesTransport): - """gRPC AsyncIO backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - Awaitable[routes_service.ComputeRoutesResponse]]: - r"""Return a callable for the compute routes method over gRPC. - - Returns the primary route along with optional alternate routes, - given a set of terminal and intermediate waypoints. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using URL parameter ``$fields`` or ``fields``, or by using an - HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available URL - parameters and - headers `__. - The value is a comma separated list of field paths. See detailed - documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of Route-level duration, distance, and polyline - (an example production setup): - ``X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline`` - - Google discourage the use of the wildcard (``*``) response field - mask, or specifying the field mask at the top level - (``routes``), because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRoutesRequest], - Awaitable[~.ComputeRoutesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_routes' not in self._stubs: - self._stubs['compute_routes'] = self.grpc_channel.unary_unary( - '/google.maps.routing.v2.Routes/ComputeRoutes', - request_serializer=routes_service.ComputeRoutesRequest.serialize, - response_deserializer=routes_service.ComputeRoutesResponse.deserialize, - ) - return self._stubs['compute_routes'] - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - Awaitable[routes_service.RouteMatrixElement]]: - r"""Return a callable for the compute route matrix method over gRPC. - - Takes in a list of origins and destinations and returns a stream - containing route information for each combination of origin and - destination. - - **NOTE:** This method requires that you specify a response field - mask in the input. You can provide the response field mask by - using the URL parameter ``$fields`` or ``fields``, or by using - the HTTP/gRPC header ``X-Goog-FieldMask`` (see the `available - URL parameters and - headers `__. - The value is a comma separated list of field paths. See this - detailed documentation about `how to construct the field - paths `__. - - For example, in this method: - - - Field mask of all available fields (for manual inspection): - ``X-Goog-FieldMask: *`` - - Field mask of route durations, distances, element status, - condition, and element indices (an example production setup): - ``X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration`` - - It is critical that you include ``status`` in your field mask as - otherwise all messages will appear to be OK. Google discourages - the use of the wildcard (``*``) response field mask, because: - - - Selecting only the fields that you need helps our server save - computation cycles, allowing us to return the result to you - with a lower latency. - - Selecting only the fields that you need in your production - job ensures stable latency performance. We might add more - response fields in the future, and those new fields might - require extra computation time. If you select all fields, or - if you select all fields at the top level, then you might - experience performance degradation because any new field we - add will be automatically included in the response. - - Selecting only the fields that you need results in a smaller - response size, and thus higher network throughput. - - Returns: - Callable[[~.ComputeRouteMatrixRequest], - Awaitable[~.RouteMatrixElement]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'compute_route_matrix' not in self._stubs: - self._stubs['compute_route_matrix'] = self.grpc_channel.unary_stream( - '/google.maps.routing.v2.Routes/ComputeRouteMatrix', - request_serializer=routes_service.ComputeRouteMatrixRequest.serialize, - response_deserializer=routes_service.RouteMatrixElement.deserialize, - ) - return self._stubs['compute_route_matrix'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'RoutesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py deleted file mode 100644 index c7fdf524b0c7..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py +++ /dev/null @@ -1,417 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.maps.routing_v2.types import routes_service - -from .base import RoutesTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class RoutesRestInterceptor: - """Interceptor for Routes. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the RoutesRestTransport. - - .. code-block:: python - class MyCustomRoutesInterceptor(RoutesRestInterceptor): - def pre_compute_route_matrix(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_route_matrix(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_compute_routes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_compute_routes(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RoutesRestTransport(interceptor=MyCustomRoutesInterceptor()) - client = RoutesClient(transport=transport) - - - """ - def pre_compute_route_matrix(self, request: routes_service.ComputeRouteMatrixRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRouteMatrixRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_route_matrix(self, response: rest_streaming.ResponseIterator) -> rest_streaming.ResponseIterator: - """Post-rpc interceptor for compute_route_matrix - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - def pre_compute_routes(self, request: routes_service.ComputeRoutesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[routes_service.ComputeRoutesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for compute_routes - - Override in a subclass to manipulate the request or metadata - before they are sent to the Routes server. - """ - return request, metadata - - def post_compute_routes(self, response: routes_service.ComputeRoutesResponse) -> routes_service.ComputeRoutesResponse: - """Post-rpc interceptor for compute_routes - - Override in a subclass to manipulate the response - after it is returned by the Routes server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class RoutesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RoutesRestInterceptor - - -class RoutesRestTransport(RoutesTransport): - """REST backend transport for Routes. - - The Routes API. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'routes.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[RoutesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or RoutesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ComputeRouteMatrix(RoutesRestStub): - def __hash__(self): - return hash("ComputeRouteMatrix") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: routes_service.ComputeRouteMatrixRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> rest_streaming.ResponseIterator: - r"""Call the compute route matrix method over HTTP. - - Args: - request (~.routes_service.ComputeRouteMatrixRequest): - The request object. ComputeRouteMatrix request message - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.routes_service.RouteMatrixElement: - Encapsulates route information - computed for an origin/destination pair - in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/distanceMatrix/v2:computeRouteMatrix', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) - pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = rest_streaming.ResponseIterator(response, routes_service.RouteMatrixElement) - resp = self._interceptor.post_compute_route_matrix(resp) - return resp - - class _ComputeRoutes(RoutesRestStub): - def __hash__(self): - return hash("ComputeRoutes") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: routes_service.ComputeRoutesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> routes_service.ComputeRoutesResponse: - r"""Call the compute routes method over HTTP. - - Args: - request (~.routes_service.ComputeRoutesRequest): - The request object. ComputeRoutes request message. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.routes_service.ComputeRoutesResponse: - ComputeRoutes the response message. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/directions/v2:computeRoutes', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_compute_routes(request, metadata) - pb_request = routes_service.ComputeRoutesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = routes_service.ComputeRoutesResponse() - pb_resp = routes_service.ComputeRoutesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_compute_routes(resp) - return resp - - @property - def compute_route_matrix(self) -> Callable[ - [routes_service.ComputeRouteMatrixRequest], - routes_service.RouteMatrixElement]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRouteMatrix(self._session, self._host, self._interceptor) # type: ignore - - @property - def compute_routes(self) -> Callable[ - [routes_service.ComputeRoutesRequest], - routes_service.ComputeRoutesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ComputeRoutes(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RoutesRestTransport', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py deleted file mode 100644 index 7323899cfc30..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .fallback_info import ( - FallbackInfo, - FallbackReason, - FallbackRoutingMode, -) -from .geocoding_results import ( - GeocodedWaypoint, - GeocodingResults, -) -from .location import ( - Location, -) -from .navigation_instruction import ( - NavigationInstruction, -) -from .polyline import ( - Polyline, - PolylineEncoding, - PolylineQuality, -) -from .route import ( - Route, - RouteLeg, - RouteLegStep, - RouteLegStepTravelAdvisory, - RouteLegTravelAdvisory, - RouteTravelAdvisory, -) -from .route_modifiers import ( - RouteModifiers, -) -from .routes_service import ( - ComputeRouteMatrixRequest, - ComputeRoutesRequest, - ComputeRoutesResponse, - RouteMatrixDestination, - RouteMatrixElement, - RouteMatrixOrigin, - RouteMatrixElementCondition, -) -from .speed_reading_interval import ( - SpeedReadingInterval, -) -from .toll_info import ( - TollInfo, -) -from .vehicle_info import ( - VehicleInfo, -) -from .waypoint import ( - Waypoint, -) - -__all__ = ( - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'Units', - 'VehicleEmissionType', - 'VehicleInfo', - 'Waypoint', -) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py deleted file mode 100644 index 51700720cfcd..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/fallback_info.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'FallbackReason', - 'FallbackRoutingMode', - 'FallbackInfo', - }, -) - - -class FallbackReason(proto.Enum): - r"""Reasons for using fallback response. - - Values: - FALLBACK_REASON_UNSPECIFIED (0): - No fallback reason specified. - SERVER_ERROR (1): - A server error happened while calculating - routes with your preferred routing mode, but we - were able to return a result calculated by an - alternative mode. - LATENCY_EXCEEDED (2): - We were not able to finish the calculation - with your preferred routing mode on time, but we - were able to return a result calculated by an - alternative mode. - """ - FALLBACK_REASON_UNSPECIFIED = 0 - SERVER_ERROR = 1 - LATENCY_EXCEEDED = 2 - - -class FallbackRoutingMode(proto.Enum): - r"""Actual routing mode used for returned fallback response. - - Values: - FALLBACK_ROUTING_MODE_UNSPECIFIED (0): - Not used. - FALLBACK_TRAFFIC_UNAWARE (1): - Indicates the ``TRAFFIC_UNAWARE`` - [google.maps.routing.v2.RoutingPreference] was used to - compute the response. - FALLBACK_TRAFFIC_AWARE (2): - Indicates the ``TRAFFIC_AWARE`` - [RoutingPreference][google.maps.routing.v2.RoutingPreference] - was used to compute the response. - """ - FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 - FALLBACK_TRAFFIC_UNAWARE = 1 - FALLBACK_TRAFFIC_AWARE = 2 - - -class FallbackInfo(proto.Message): - r"""Information related to how and why a fallback result was - used. If this field is set, then it means the server used a - different routing mode from your preferred mode as fallback. - - Attributes: - routing_mode (google.maps.routing_v2.types.FallbackRoutingMode): - Routing mode used for the response. If - fallback was triggered, the mode may be - different from routing preference set in the - original client request. - reason (google.maps.routing_v2.types.FallbackReason): - The reason why fallback response was used - instead of the original response. This field is - only populated when the fallback mode is - triggered and the fallback response is returned. - """ - - routing_mode: 'FallbackRoutingMode' = proto.Field( - proto.ENUM, - number=1, - enum='FallbackRoutingMode', - ) - reason: 'FallbackReason' = proto.Field( - proto.ENUM, - number=2, - enum='FallbackReason', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py deleted file mode 100644 index 577d97bc2e95..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/geocoding_results.py +++ /dev/null @@ -1,127 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'GeocodingResults', - 'GeocodedWaypoint', - }, -) - - -class GeocodingResults(proto.Message): - r"""Contains - [GeocodedWaypoints][google.maps.routing.v2.GeocodedWaypoint] for - origin, destination and intermediate waypoints. Only populated for - address waypoints. - - Attributes: - origin (google.maps.routing_v2.types.GeocodedWaypoint): - Origin geocoded waypoint. - destination (google.maps.routing_v2.types.GeocodedWaypoint): - Destination geocoded waypoint. - intermediates (MutableSequence[google.maps.routing_v2.types.GeocodedWaypoint]): - A list of intermediate geocoded waypoints - each containing an index field that corresponds - to the zero-based position of the waypoint in - the order they were specified in the request. - """ - - origin: 'GeocodedWaypoint' = proto.Field( - proto.MESSAGE, - number=1, - message='GeocodedWaypoint', - ) - destination: 'GeocodedWaypoint' = proto.Field( - proto.MESSAGE, - number=2, - message='GeocodedWaypoint', - ) - intermediates: MutableSequence['GeocodedWaypoint'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='GeocodedWaypoint', - ) - - -class GeocodedWaypoint(proto.Message): - r"""Details about the locations used as waypoints. Only populated - for address waypoints. Includes details about the geocoding - results for the purposes of determining what the address was - geocoded to. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - geocoder_status (google.rpc.status_pb2.Status): - Indicates the status code resulting from the - geocoding operation. - intermediate_waypoint_request_index (int): - The index of the corresponding intermediate - waypoint in the request. Only populated if the - corresponding waypoint is an intermediate - waypoint. - - This field is a member of `oneof`_ ``_intermediate_waypoint_request_index``. - type_ (MutableSequence[str]): - The type(s) of the result, in the form of - zero or more type tags. Supported types: - https://developers.google.com/maps/documentation/geocoding/requests-geocoding#Types - partial_match (bool): - Indicates that the geocoder did not return an - exact match for the original request, though it - was able to match part of the requested address. - You may wish to examine the original request for - misspellings and/or an incomplete address. - place_id (str): - The place ID for this result. - """ - - geocoder_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - intermediate_waypoint_request_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - type_: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - partial_match: bool = proto.Field( - proto.BOOL, - number=4, - ) - place_id: str = proto.Field( - proto.STRING, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py deleted file mode 100644 index 10724419f9a8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Location', - }, -) - - -class Location(proto.Message): - r"""Encapsulates a location (a geographic point, and an optional - heading). - - Attributes: - lat_lng (google.type.latlng_pb2.LatLng): - The waypoint's geographic coordinates. - heading (google.protobuf.wrappers_pb2.Int32Value): - The compass heading associated with the direction of the - flow of traffic. This value is used to specify the side of - the road to use for pickup and drop-off. Heading values can - be from 0 to 360, where 0 specifies a heading of due North, - 90 specifies a heading of due East, etc. You can use this - field only for ``DRIVE`` and ``TWO_WHEELER`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. - """ - - lat_lng: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - heading: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py deleted file mode 100644 index 60e5cd3cb9c6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py +++ /dev/null @@ -1,96 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Maneuver', - }, -) - - -class Maneuver(proto.Enum): - r"""A set of values that specify the navigation action to take - for the current step (e.g., turn left, merge, straight, etc.). - - Values: - MANEUVER_UNSPECIFIED (0): - Not used. - TURN_SLIGHT_LEFT (1): - Turn slightly to the left. - TURN_SHARP_LEFT (2): - Turn sharply to the left. - UTURN_LEFT (3): - Make a left u-turn. - TURN_LEFT (4): - Turn left. - TURN_SLIGHT_RIGHT (5): - Turn slightly to the right. - TURN_SHARP_RIGHT (6): - Turn sharply to the right. - UTURN_RIGHT (7): - Make a right u-turn. - TURN_RIGHT (8): - Turn right. - STRAIGHT (9): - Go straight. - RAMP_LEFT (10): - Take the left ramp. - RAMP_RIGHT (11): - Take the right ramp. - MERGE (12): - Merge into traffic. - FORK_LEFT (13): - Take the left fork. - FORK_RIGHT (14): - Take the right fork. - FERRY (15): - Take the ferry. - FERRY_TRAIN (16): - Take the train leading onto the ferry. - ROUNDABOUT_LEFT (17): - Turn left at the roundabout. - ROUNDABOUT_RIGHT (18): - Turn right at the roundabout. - """ - MANEUVER_UNSPECIFIED = 0 - TURN_SLIGHT_LEFT = 1 - TURN_SHARP_LEFT = 2 - UTURN_LEFT = 3 - TURN_LEFT = 4 - TURN_SLIGHT_RIGHT = 5 - TURN_SHARP_RIGHT = 6 - UTURN_RIGHT = 7 - TURN_RIGHT = 8 - STRAIGHT = 9 - RAMP_LEFT = 10 - RAMP_RIGHT = 11 - MERGE = 12 - FORK_LEFT = 13 - FORK_RIGHT = 14 - FERRY = 15 - FERRY_TRAIN = 16 - ROUNDABOUT_LEFT = 17 - ROUNDABOUT_RIGHT = 18 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py deleted file mode 100644 index dc8b69e76ccd..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/navigation_instruction.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import maneuver as gmr_maneuver - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'NavigationInstruction', - }, -) - - -class NavigationInstruction(proto.Message): - r"""Encapsulates navigation instructions for a - [RouteLegStep][google.maps.routing.v2.RouteLegStep] - - Attributes: - maneuver (google.maps.routing_v2.types.Maneuver): - Encapsulates the navigation instructions for - the current step (e.g., turn left, merge, - straight, etc.). This field determines which - icon to display. - instructions (str): - Instructions for navigating this step. - """ - - maneuver: gmr_maneuver.Maneuver = proto.Field( - proto.ENUM, - number=1, - enum=gmr_maneuver.Maneuver, - ) - instructions: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py deleted file mode 100644 index 4d9630691288..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/polyline.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'PolylineQuality', - 'PolylineEncoding', - 'Polyline', - }, -) - - -class PolylineQuality(proto.Enum): - r"""A set of values that specify the quality of the polyline. - - Values: - POLYLINE_QUALITY_UNSPECIFIED (0): - No polyline quality preference specified. Defaults to - ``OVERVIEW``. - HIGH_QUALITY (1): - Specifies a high-quality polyline - which is composed using - more points than ``OVERVIEW``, at the cost of increased - response size. Use this value when you need more precision. - OVERVIEW (2): - Specifies an overview polyline - which is composed using a - small number of points. Use this value when displaying an - overview of the route. Using this option has a lower request - latency compared to using the ``HIGH_QUALITY`` option. - """ - POLYLINE_QUALITY_UNSPECIFIED = 0 - HIGH_QUALITY = 1 - OVERVIEW = 2 - - -class PolylineEncoding(proto.Enum): - r"""Specifies the preferred type of polyline to be returned. - - Values: - POLYLINE_ENCODING_UNSPECIFIED (0): - No polyline type preference specified. Defaults to - ``ENCODED_POLYLINE``. - ENCODED_POLYLINE (1): - Specifies a polyline encoded using the `polyline encoding - algorithm `__. - GEO_JSON_LINESTRING (2): - Specifies a polyline using the `GeoJSON LineString - format `__ - """ - POLYLINE_ENCODING_UNSPECIFIED = 0 - ENCODED_POLYLINE = 1 - GEO_JSON_LINESTRING = 2 - - -class Polyline(proto.Message): - r"""Encapsulates an encoded polyline. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - encoded_polyline (str): - The string encoding of the polyline using the `polyline - encoding - algorithm `__ - - This field is a member of `oneof`_ ``polyline_type``. - geo_json_linestring (google.protobuf.struct_pb2.Struct): - Specifies a polyline using the `GeoJSON LineString - format `__ - - This field is a member of `oneof`_ ``polyline_type``. - """ - - encoded_polyline: str = proto.Field( - proto.STRING, - number=1, - oneof='polyline_type', - ) - geo_json_linestring: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - oneof='polyline_type', - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py deleted file mode 100644 index 9c25ea98abc3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py +++ /dev/null @@ -1,411 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.geo.type import viewport_pb2 # type: ignore -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import navigation_instruction as gmr_navigation_instruction -from google.maps.routing_v2.types import polyline as gmr_polyline -from google.maps.routing_v2.types import route_label -from google.maps.routing_v2.types import speed_reading_interval -from google.maps.routing_v2.types import toll_info as gmr_toll_info -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Route', - 'RouteTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteLegStepTravelAdvisory', - 'RouteLeg', - 'RouteLegStep', - }, -) - - -class Route(proto.Message): - r"""Encapsulates a route, which consists of a series of connected - road segments that join beginning, ending, and intermediate - waypoints. - - Attributes: - route_labels (MutableSequence[google.maps.routing_v2.types.RouteLabel]): - Labels for the ``Route`` that are useful to identify - specific properties of the route to compare against others. - legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): - A collection of legs (path segments between waypoints) that - make-up the route. Each leg corresponds to the trip between - two non-\ ``via`` - [Waypoints][google.maps.routing.v2.Waypoint]. For example, a - route with no intermediate waypoints has only one leg. A - route that includes one non-\ ``via`` intermediate waypoint - has two legs. A route that includes one ``via`` intermediate - waypoint has one leg. The order of the legs matches the - order of Waypoints from ``origin`` to ``intermediates`` to - ``destination``. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the route - without taking traffic conditions into - consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall route polyline. This polyline will be the - combined polyline of all ``legs``. - description (str): - A description of the route. - warnings (MutableSequence[str]): - An array of warnings to show when displaying - the route. - viewport (google.geo.type.viewport_pb2.Viewport): - The viewport bounding box of the polyline. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. - route_token (str): - Web-safe base64 encoded route token that can be passed to - NavigationSDK, which allows the Navigation SDK to - reconstruct the route during navigation, and in the event of - rerouting honor the original intention when Routes - ComputeRoutes is called. Customers should treat this token - as an opaque blob. NOTE: ``Route.route_token`` is only - available for requests that have set - ``ComputeRoutesRequest.routing_preference`` to - ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``. - ``Route.route_token`` is also not supported for requests - that have Via waypoints. - """ - - route_labels: MutableSequence[route_label.RouteLabel] = proto.RepeatedField( - proto.ENUM, - number=13, - enum=route_label.RouteLabel, - ) - legs: MutableSequence['RouteLeg'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteLeg', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=2, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_polyline.Polyline, - ) - description: str = proto.Field( - proto.STRING, - number=6, - ) - warnings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - viewport: viewport_pb2.Viewport = proto.Field( - proto.MESSAGE, - number=8, - message=viewport_pb2.Viewport, - ) - travel_advisory: 'RouteTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=9, - message='RouteTravelAdvisory', - ) - route_token: str = proto.Field( - proto.STRING, - number=12, - ) - - -class RouteTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction - etc. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Encapsulates information about tolls on the Route. This - field is only populated if we expect there are tolls on the - Route. If this field is set but the estimated_price subfield - is not populated, we expect that road contains tolls but we - do not know an estimated price. If this field is not set, - then we expect there is no toll on the Route. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the route without overlap. The - start point of a specified interval is the same as the end - point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - fuel_consumption_microliters (int): - The fuel consumption prediction in - microliters. - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=speed_reading_interval.SpeedReadingInterval, - ) - fuel_consumption_microliters: int = proto.Field( - proto.INT64, - number=5, - ) - - -class RouteLegTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction - etc. on a route leg. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Encapsulates information about tolls on the specific - RouteLeg. This field is only populated if we expect there - are tolls on the RouteLeg. If this field is set but the - estimated_price subfield is not populated, we expect that - road contains tolls but we do not know an estimated price. - If this field does not exist, then there is no toll on the - RouteLeg. - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - Speed reading intervals detailing traffic density. - Applicable in case of ``TRAFFIC_AWARE`` and - ``TRAFFIC_AWARE_OPTIMAL`` routing preferences. The intervals - cover the entire polyline of the RouteLg without overlap. - The start point of a specified interval is the same as the - end point of the preceding interval. - - Example: - - :: - - polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - speed_reading_intervals: [A,C), [C,D), [D,G). - """ - - toll_info: gmr_toll_info.TollInfo = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_toll_info.TollInfo, - ) - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLegStepTravelAdvisory(proto.Message): - r"""Encapsulates the additional information that the user should - be informed about, such as possible traffic zone restriction on - a leg step. - - Attributes: - speed_reading_intervals (MutableSequence[google.maps.routing_v2.types.SpeedReadingInterval]): - NOTE: This field is not currently populated. - """ - - speed_reading_intervals: MutableSequence[speed_reading_interval.SpeedReadingInterval] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=speed_reading_interval.SpeedReadingInterval, - ) - - -class RouteLeg(proto.Message): - r"""Encapsulates a segment between non-\ ``via`` waypoints. - - Attributes: - distance_meters (int): - The travel distance of the route leg, in - meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the leg. If the - ``route_preference`` is set to ``TRAFFIC_UNAWARE``, then - this value is the same as ``static_duration``. If the - ``route_preference`` is either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the leg, - calculated without taking traffic conditions - into consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall polyline for this leg. This includes that each - ``step``'s polyline. - start_location (google.maps.routing_v2.types.Location): - The start location of this leg. This might be different from - the provided ``origin``. For example, when the provided - ``origin`` is not near a road, this is a point on the road. - end_location (google.maps.routing_v2.types.Location): - The end location of this leg. This might be different from - the provided ``destination``. For example, when the provided - ``destination`` is not near a road, this is a point on the - road. - steps (MutableSequence[google.maps.routing_v2.types.RouteLegStep]): - An array of steps denoting segments within - this leg. Each step represents one navigation - instruction. - travel_advisory (google.maps.routing_v2.types.RouteLegTravelAdvisory): - Encapsulates the additional information that - the user should be informed about, such as - possible traffic zone restriction etc. on a - route leg. - """ - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=4, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=6, - message=location.Location, - ) - steps: MutableSequence['RouteLegStep'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='RouteLegStep', - ) - travel_advisory: 'RouteLegTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=8, - message='RouteLegTravelAdvisory', - ) - - -class RouteLegStep(proto.Message): - r"""Encapsulates a segment of a - [RouteLeg][google.maps.routing.v2.RouteLeg]. A step corresponds to a - single navigation instruction. Route legs are made up of steps. - - Attributes: - distance_meters (int): - The travel distance of this step, in meters. - In some circumstances, this field might not have - a value. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of travel through this step - without taking traffic conditions into - consideration. In some circumstances, this field - might not have a value. - polyline (google.maps.routing_v2.types.Polyline): - The polyline associated with this step. - start_location (google.maps.routing_v2.types.Location): - The start location of this step. - end_location (google.maps.routing_v2.types.Location): - The end location of this step. - navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): - Navigation instructions. - travel_advisory (google.maps.routing_v2.types.RouteLegStepTravelAdvisory): - Encapsulates the additional information that - the user should be informed about, such as - possible traffic zone restriction on a leg step. - """ - - distance_meters: int = proto.Field( - proto.INT32, - number=1, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - polyline: gmr_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_polyline.Polyline, - ) - start_location: location.Location = proto.Field( - proto.MESSAGE, - number=4, - message=location.Location, - ) - end_location: location.Location = proto.Field( - proto.MESSAGE, - number=5, - message=location.Location, - ) - navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( - proto.MESSAGE, - number=6, - message=gmr_navigation_instruction.NavigationInstruction, - ) - travel_advisory: 'RouteLegStepTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=7, - message='RouteLegStepTravelAdvisory', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py deleted file mode 100644 index e0105d9b95bd..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteLabel', - }, -) - - -class RouteLabel(proto.Enum): - r"""Labels for the [Route][google.maps.routing.v2.Route] that are useful - to identify specific properties of the route to compare against - others. - - Values: - ROUTE_LABEL_UNSPECIFIED (0): - Default - not used. - DEFAULT_ROUTE (1): - The default "best" route returned for the - route computation. - DEFAULT_ROUTE_ALTERNATE (2): - An alternative to the default "best" route. Routes like this - will be returned when - [compute_alternative_routes][google.maps.routing.v2.ComputeRoutesRequest.compute_alternative_routes] - is specified. - FUEL_EFFICIENT (3): - Fuel efficient route. Routes labeled with - this value are determined to be optimized for - Eco parameters such as fuel consumption. - """ - ROUTE_LABEL_UNSPECIFIED = 0 - DEFAULT_ROUTE = 1 - DEFAULT_ROUTE_ALTERNATE = 2 - FUEL_EFFICIENT = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py deleted file mode 100644 index 589dc7c38f4a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_modifiers.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import toll_passes as gmr_toll_passes -from google.maps.routing_v2.types import vehicle_info as gmr_vehicle_info - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteModifiers', - }, -) - - -class RouteModifiers(proto.Message): - r"""Encapsulates a set of optional conditions to satisfy when - calculating the routes. - - Attributes: - avoid_tolls (bool): - Specifies whether to avoid toll roads where reasonable. - Preference will be given to routes not containing toll - roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. - avoid_highways (bool): - Specifies whether to avoid highways where reasonable. - Preference will be given to routes not containing highways. - Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. - avoid_ferries (bool): - Specifies whether to avoid ferries where reasonable. - Preference will be given to routes not containing travel by - ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. - avoid_indoor (bool): - Specifies whether to avoid navigating indoors where - reasonable. Preference will be given to routes not - containing indoor navigation. Applies only to the ``WALK`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. - vehicle_info (google.maps.routing_v2.types.VehicleInfo): - Specifies the vehicle information. - toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): - Encapsulates information about toll passes. If toll passes - are provided, the API tries to return the pass price. If - toll passes are not provided, the API treats the toll pass - as unknown and tries to return the cash price. Applies only - to the ``DRIVE`` and ``TWO_WHEELER`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. - """ - - avoid_tolls: bool = proto.Field( - proto.BOOL, - number=1, - ) - avoid_highways: bool = proto.Field( - proto.BOOL, - number=2, - ) - avoid_ferries: bool = proto.Field( - proto.BOOL, - number=3, - ) - avoid_indoor: bool = proto.Field( - proto.BOOL, - number=4, - ) - vehicle_info: gmr_vehicle_info.VehicleInfo = proto.Field( - proto.MESSAGE, - number=5, - message=gmr_vehicle_info.VehicleInfo, - ) - toll_passes: MutableSequence[gmr_toll_passes.TollPass] = proto.RepeatedField( - proto.ENUM, - number=6, - enum=gmr_toll_passes.TollPass, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py deleted file mode 100644 index 239957aada7f..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteTravelMode', - }, -) - - -class RouteTravelMode(proto.Enum): - r"""A set of values used to specify the mode of travel. NOTE: ``WALK``, - ``BICYCLE``, and ``TWO_WHEELER`` routes are in beta and might - sometimes be missing clear sidewalks, pedestrian paths, or bicycling - paths. You must display this warning to the user for all walking, - bicycling, and two-wheel routes that you display in your app. - - Values: - TRAVEL_MODE_UNSPECIFIED (0): - No travel mode specified. Defaults to ``DRIVE``. - DRIVE (1): - Travel by passenger car. - BICYCLE (2): - Travel by bicycle. - WALK (3): - Travel by walking. - TWO_WHEELER (4): - Two-wheeled, motorized vehicle. For example, motorcycle. - Note that this differs from the ``BICYCLE`` travel mode - which covers human-powered mode. - """ - TRAVEL_MODE_UNSPECIFIED = 0 - DRIVE = 1 - BICYCLE = 2 - WALK = 3 - TWO_WHEELER = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py deleted file mode 100644 index f95ca0ed0aca..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py +++ /dev/null @@ -1,544 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import fallback_info as gmr_fallback_info -from google.maps.routing_v2.types import geocoding_results as gmr_geocoding_results -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers as gmr_route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routing_preference as gmr_routing_preference -from google.maps.routing_v2.types import units as gmr_units -from google.maps.routing_v2.types import waypoint as gmr_waypoint -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RouteMatrixElementCondition', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'ComputeRouteMatrixRequest', - 'RouteMatrixOrigin', - 'RouteMatrixDestination', - 'RouteMatrixElement', - }, -) - - -class RouteMatrixElementCondition(proto.Enum): - r"""The condition of the route being returned. - - Values: - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED (0): - Only used when the ``status`` of the element is not OK. - ROUTE_EXISTS (1): - A route was found, and the corresponding - information was filled out for the element. - ROUTE_NOT_FOUND (2): - No route could be found. Fields containing route - information, such as ``distance_meters`` or ``duration``, - will not be filled out in the element. - """ - ROUTE_MATRIX_ELEMENT_CONDITION_UNSPECIFIED = 0 - ROUTE_EXISTS = 1 - ROUTE_NOT_FOUND = 2 - - -class ComputeRoutesRequest(proto.Message): - r"""ComputeRoutes request message. - - Attributes: - origin (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint. - destination (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint. - intermediates (MutableSequence[google.maps.routing_v2.types.Waypoint]): - Optional. A set of waypoints along the route - (excluding terminal points), for either stopping - at or passing by. Up to 25 intermediate - waypoints are supported. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, then an error is returned. You can - specify this option only when the ``travel_mode`` is - ``DRIVE`` or ``TWO_WHEELER``, otherwise the request fails. - polyline_quality (google.maps.routing_v2.types.PolylineQuality): - Optional. Specifies your preference for the - quality of the polyline. - polyline_encoding (google.maps.routing_v2.types.PolylineEncoding): - Optional. Specifies the preferred encoding - for the polyline. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't - set this value, then this value defaults to the - time that you made the request. If you set this - value to a time that has already occurred, then - the request fails. - compute_alternative_routes (bool): - Optional. Specifies whether to calculate - alternate routes in addition to the route. No - alternative routes are returned for requests - that have intermediate waypoints. - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. A set of conditions to satisfy that - affect the way routes are calculated. - language_code (str): - Optional. The BCP-47 language code, such as "en-US" or - "sr-Latn". For more information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - See `Language - Support `__ - for the list of supported languages. When you don't provide - this value, the display language is inferred from the - location of the route request. - region_code (str): - Optional. The region code, specified as a ccTLD ("top-level - domain") two-character value. For more information see - https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains - units (google.maps.routing_v2.types.Units): - Optional. Specifies the units of measure for the display - fields. This includes the ``instruction`` field in - [NavigationInstruction][google.maps.routing.v2.NavigationInstruction]. - The units of measure used for the route, leg, step distance, - and duration are not affected by this value. If you don't - provide this value, then the display units are inferred from - the location of the request. - requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): - Optional. Specifies what reference routes to calculate as - part of the request in addition to the default route. A - reference route is a route with a different route - calculation objective than the default route. For example a - ``FUEL_EFFICIENT`` reference route calculation takes into - account various parameters that would generate an optimal - fuel efficient route. - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - """ - class ReferenceRoute(proto.Enum): - r"""A supported reference route on the ComputeRoutesRequest. - - Values: - REFERENCE_ROUTE_UNSPECIFIED (0): - Not used. Requests containing this value - fail. - FUEL_EFFICIENT (1): - Fuel efficient route. Routes labeled with - this value are determined to be optimized for - parameters such as fuel consumption. - """ - REFERENCE_ROUTE_UNSPECIFIED = 0 - FUEL_EFFICIENT = 1 - - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the route(s). - FUEL_CONSUMPTION (2): - Estimated fuel consumption for the route(s). - TRAFFIC_ON_POLYLINE (3): - Traffic aware polylines for the route(s). - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - FUEL_CONSUMPTION = 2 - TRAFFIC_ON_POLYLINE = 3 - - origin: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - destination: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_waypoint.Waypoint, - ) - intermediates: MutableSequence[gmr_waypoint.Waypoint] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=gmr_waypoint.Waypoint, - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=4, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=5, - enum=gmr_routing_preference.RoutingPreference, - ) - polyline_quality: polyline.PolylineQuality = proto.Field( - proto.ENUM, - number=6, - enum=polyline.PolylineQuality, - ) - polyline_encoding: polyline.PolylineEncoding = proto.Field( - proto.ENUM, - number=12, - enum=polyline.PolylineEncoding, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - compute_alternative_routes: bool = proto.Field( - proto.BOOL, - number=8, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=9, - message=gmr_route_modifiers.RouteModifiers, - ) - language_code: str = proto.Field( - proto.STRING, - number=10, - ) - region_code: str = proto.Field( - proto.STRING, - number=16, - ) - units: gmr_units.Units = proto.Field( - proto.ENUM, - number=11, - enum=gmr_units.Units, - ) - requested_reference_routes: MutableSequence[ReferenceRoute] = proto.RepeatedField( - proto.ENUM, - number=14, - enum=ReferenceRoute, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=15, - enum=ExtraComputation, - ) - - -class ComputeRoutesResponse(proto.Message): - r"""ComputeRoutes the response message. - - Attributes: - routes (MutableSequence[google.maps.routing_v2.types.Route]): - Contains an array of computed routes (up to three) when you - specify compute_alternatives_routes, and contains just one - route when you don't. When this array contains multiple - entries, the first one is the most recommended route. If the - array is empty, then it means no route could be found. - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route results with all of the input - preferences, it may fallback to using a - different way of computation. When fallback mode - is used, this field contains detailed info about - the fallback response. Otherwise this field is - unset. - geocoding_results (google.maps.routing_v2.types.GeocodingResults): - Contains geocoding response info for - waypoints specified as addresses. - """ - - routes: MutableSequence[route.Route] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=route.Route, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_fallback_info.FallbackInfo, - ) - geocoding_results: gmr_geocoding_results.GeocodingResults = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_geocoding_results.GeocodingResults, - ) - - -class ComputeRouteMatrixRequest(proto.Message): - r"""ComputeRouteMatrix request message - - Attributes: - origins (MutableSequence[google.maps.routing_v2.types.RouteMatrixOrigin]): - Required. Array of origins, which determines the rows of the - response matrix. Several size restrictions apply to the - cardinality of origins and destinations: - - - The number of elements (origins × destinations) must be - no greater than 625 in any case. - - The number of elements (origins × destinations) must be - no greater than 100 if routing_preference is set to - ``TRAFFIC_AWARE_OPTIMAL``. - - The number of waypoints (origins + destinations) - specified as ``place_id`` must be no greater than 50. - destinations (MutableSequence[google.maps.routing_v2.types.RouteMatrixDestination]): - Required. Array of destinations, which - determines the columns of the response matrix. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - Optional. Specifies the mode of - transportation. - routing_preference (google.maps.routing_v2.types.RoutingPreference): - Optional. Specifies how to compute the route. The server - attempts to use the selected routing preference to compute - the route. If the routing preference results in an error or - an extra long latency, an error is returned. You can specify - this option only when the ``travel_mode`` is ``DRIVE`` or - ``TWO_WHEELER``, otherwise the request fails. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The departure time. If you don't - set this value, this defaults to the time that - you made the request. If you set this value to a - time that has already occurred, the request - fails. - language_code (str): - Optional. The BCP-47 language code, such as "en-US" or - "sr-Latn". For more information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - See `Language - Support `__ - for the list of supported languages. When you don't provide - this value, the display language is inferred from the - location of the first origin. - region_code (str): - Optional. The region code, specified as a ccTLD ("top-level - domain") two-character value. For more information see - https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains - extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): - Optional. A list of extra computations which - may be used to complete the request. Note: These - extra computations may return extra fields on - the response. These extra fields must also be - specified in the field mask to be returned in - the response. - """ - class ExtraComputation(proto.Enum): - r"""Extra computations to perform while completing the request. - - Values: - EXTRA_COMPUTATION_UNSPECIFIED (0): - Not used. Requests containing this value will - fail. - TOLLS (1): - Toll information for the matrix element(s). - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - - origins: MutableSequence['RouteMatrixOrigin'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteMatrixOrigin', - ) - destinations: MutableSequence['RouteMatrixDestination'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='RouteMatrixDestination', - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=3, - enum=route_travel_mode.RouteTravelMode, - ) - routing_preference: gmr_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=4, - enum=gmr_routing_preference.RoutingPreference, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - language_code: str = proto.Field( - proto.STRING, - number=6, - ) - region_code: str = proto.Field( - proto.STRING, - number=9, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=8, - enum=ExtraComputation, - ) - - -class RouteMatrixOrigin(proto.Message): - r"""A single origin for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Origin waypoint - route_modifiers (google.maps.routing_v2.types.RouteModifiers): - Optional. Modifiers for every route that - takes this as the origin - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - route_modifiers: gmr_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_route_modifiers.RouteModifiers, - ) - - -class RouteMatrixDestination(proto.Message): - r"""A single destination for ComputeRouteMatrixRequest - - Attributes: - waypoint (google.maps.routing_v2.types.Waypoint): - Required. Destination waypoint - """ - - waypoint: gmr_waypoint.Waypoint = proto.Field( - proto.MESSAGE, - number=1, - message=gmr_waypoint.Waypoint, - ) - - -class RouteMatrixElement(proto.Message): - r"""Encapsulates route information computed for an - origin/destination pair in the ComputeRouteMatrix API. This - proto can be streamed to the client. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - origin_index (int): - Zero-based index of the origin in the - request. - - This field is a member of `oneof`_ ``_origin_index``. - destination_index (int): - Zero-based index of the destination in the - request. - - This field is a member of `oneof`_ ``_destination_index``. - status (google.rpc.status_pb2.Status): - Error status code for this element. - condition (google.maps.routing_v2.types.RouteMatrixElementCondition): - Indicates whether the route was found or not. - Independent of status. - distance_meters (int): - The travel distance of the route, in meters. - duration (google.protobuf.duration_pb2.Duration): - The length of time needed to navigate the route. If you set - the - [routing_preference][google.maps.routing.v2.ComputeRouteMatrixRequest.routing_preference] - to ``TRAFFIC_UNAWARE``, then this value is the same as - ``static_duration``. If you set the ``routing_preference`` - to either ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``, - then this value is calculated taking traffic conditions into - account. - static_duration (google.protobuf.duration_pb2.Duration): - The duration of traveling through the route - without taking traffic conditions into - consideration. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. For - example: restriction information and toll - information - fallback_info (google.maps.routing_v2.types.FallbackInfo): - In some cases when the server is not able to - compute the route with the given preferences for - this particular origin/destination pair, it may - fall back to using a different mode of - computation. When fallback mode is used, this - field contains detailed information about the - fallback response. Otherwise this field is - unset. - """ - - origin_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - destination_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - message=status_pb2.Status, - ) - condition: 'RouteMatrixElementCondition' = proto.Field( - proto.ENUM, - number=9, - enum='RouteMatrixElementCondition', - ) - distance_meters: int = proto.Field( - proto.INT32, - number=4, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - static_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - travel_advisory: route.RouteTravelAdvisory = proto.Field( - proto.MESSAGE, - number=7, - message=route.RouteTravelAdvisory, - ) - fallback_info: gmr_fallback_info.FallbackInfo = proto.Field( - proto.MESSAGE, - number=8, - message=gmr_fallback_info.FallbackInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py deleted file mode 100644 index d303b4947306..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'RoutingPreference', - }, -) - - -class RoutingPreference(proto.Enum): - r"""A set of values that specify factors to take into - consideration when calculating the route. - - Values: - ROUTING_PREFERENCE_UNSPECIFIED (0): - No routing preference specified. Default to - ``TRAFFIC_UNAWARE``. - TRAFFIC_UNAWARE (1): - Computes routes without taking live traffic conditions into - consideration. Suitable when traffic conditions don't matter - or are not applicable. Using this value produces the lowest - latency. Note: For - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] - ``DRIVE`` and ``TWO_WHEELER`` choice of route and duration - are based on road network and average time-independent - traffic conditions. Results for a given request may vary - over time due to changes in the road network, updated - average traffic conditions, and the distributed nature of - the service. Results may also vary between nearly-equivalent - routes at any time or frequency. - TRAFFIC_AWARE (2): - Calculates routes taking live traffic conditions into - consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, - some optimizations are applied to significantly reduce - latency. - TRAFFIC_AWARE_OPTIMAL (3): - Calculates the routes taking live traffic - conditions into consideration, without applying - most performance optimizations. Using this value - produces the highest latency. - """ - ROUTING_PREFERENCE_UNSPECIFIED = 0 - TRAFFIC_UNAWARE = 1 - TRAFFIC_AWARE = 2 - TRAFFIC_AWARE_OPTIMAL = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py deleted file mode 100644 index e68d9247b109..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/speed_reading_interval.py +++ /dev/null @@ -1,92 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'SpeedReadingInterval', - }, -) - - -class SpeedReadingInterval(proto.Message): - r"""Traffic density indicator on a contiguous segment of a polyline or - path. Given a path with points P_0, P_1, ... , P_N (zero-based - index), the SpeedReadingInterval defines an interval and describes - its traffic using the following categories. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - start_polyline_point_index (int): - The starting index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_start_polyline_point_index``. - end_polyline_point_index (int): - The ending index of this interval in the - polyline. - - This field is a member of `oneof`_ ``_end_polyline_point_index``. - speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): - Traffic speed in this interval. - - This field is a member of `oneof`_ ``speed_type``. - """ - class Speed(proto.Enum): - r"""The classification of polyline speed based on traffic data. - - Values: - SPEED_UNSPECIFIED (0): - Default value. This value is unused. - NORMAL (1): - Normal speed, no slowdown is detected. - SLOW (2): - Slowdown detected, but no traffic jam formed. - TRAFFIC_JAM (3): - Traffic jam detected. - """ - SPEED_UNSPECIFIED = 0 - NORMAL = 1 - SLOW = 2 - TRAFFIC_JAM = 3 - - start_polyline_point_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - end_polyline_point_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - speed: Speed = proto.Field( - proto.ENUM, - number=3, - oneof='speed_type', - enum=Speed, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py deleted file mode 100644 index 1b7d73fd2f76..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_info.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.type import money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TollInfo', - }, -) - - -class TollInfo(proto.Message): - r"""Encapsulates toll information on a - [Route][google.maps.routing.v2.Route] or on a - [RouteLeg][google.maps.routing.v2.RouteLeg]. - - Attributes: - estimated_price (MutableSequence[google.type.money_pb2.Money]): - The monetary amount of tolls for the corresponding - [Route][google.maps.routing.v2.Route] or - [RouteLeg][google.maps.routing.v2.RouteLeg]. This list - contains a money amount for each currency that is expected - to be charged by the toll stations. Typically this list will - contain only one item for routes with tolls in one currency. - For international trips, this list may contain multiple - items to reflect tolls in different currencies. - """ - - estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=money_pb2.Money, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py deleted file mode 100644 index 0faa9d9865cf..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py +++ /dev/null @@ -1,351 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TollPass', - }, -) - - -class TollPass(proto.Enum): - r"""List of toll passes around the world that we support. - - Values: - TOLL_PASS_UNSPECIFIED (0): - Not used. If this value is used, then the - request fails. - AU_ETOLL_TAG (82): - Sydney toll pass. See additional details at - https://www.myetoll.com.au. - AU_EWAY_TAG (83): - Sydney toll pass. See additional details at - https://www.tollpay.com.au. - AU_LINKT (2): - Australia-wide toll pass. - See additional details at - https://www.linkt.com.au/. - AR_TELEPASE (3): - Argentina toll pass. See additional details - at https://telepase.com.ar - BR_AUTO_EXPRESO (81): - Brazil toll pass. See additional details at - https://www.autoexpreso.com - BR_CONECTCAR (7): - Brazil toll pass. See additional details at - https://conectcar.com. - BR_MOVE_MAIS (8): - Brazil toll pass. See additional details at - https://movemais.com. - BR_PASSA_RAPIDO (88): - Brazil toll pass. See additional details at - https://pasorapido.gob.do/ - BR_SEM_PARAR (9): - Brazil toll pass. See additional details at - https://www.semparar.com.br. - BR_TAGGY (10): - Brazil toll pass. See additional details at - https://taggy.com.br. - BR_VELOE (11): - Brazil toll pass. See additional details at - https://veloe.com.br/site/onde-usar. - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD (84): - Canada to United States border crossing. - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD (85): - Canada to United States border crossing. - CA_US_BLUE_WATER_EDGE_PASS (18): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_CONNEXION (19): - Ontario, Canada to Michigan, United States - border crossing. - CA_US_NEXUS_CARD (20): - Canada to United States border crossing. - ID_E_TOLL (16): - Indonesia. - E-card provided by multiple banks used to pay - for tolls. All e-cards via banks are charged the - same so only one enum value is needed. E.g. - - Bank Mandiri - https://www.bankmandiri.co.id/e-money - BCA - https://www.bca.co.id/flazz - - BNI - https://www.bni.co.id/id-id/ebanking/tapcash - IN_FASTAG (78): - India. - IN_LOCAL_HP_PLATE_EXEMPT (79): - India, HP state plate exemption. - MX_IAVE (90): - Mexico toll pass. - https://iave.capufe.gob.mx/#/ - MX_PASE (91): - Mexico - https://www.pase.com.mx - MX_QUICKPASS (93): - Mexico - https://operadoravial.com/quick-pass/ - MX_SISTEMA_TELEPEAJE_CHIHUAHUA (89): - http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf - MX_TAG_IAVE (12): - Mexico - MX_TAG_TELEVIA (13): - Mexico toll pass company. One of many - operating in Mexico City. See additional details - at https://www.televia.com.mx. - MX_TELEVIA (92): - Mexico toll pass company. One of many - operating in Mexico City. - https://www.televia.com.mx - MX_VIAPASS (14): - Mexico toll pass. See additional details at - https://www.viapass.com.mx/viapass/web_home.aspx. - US_AL_FREEDOM_PASS (21): - AL, USA. - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS (22): - AK, USA. - US_CA_FASTRAK (4): - CA, USA. - US_CA_FASTRAK_CAV_STICKER (86): - Indicates driver has any FasTrak pass in - addition to the DMV issued Clean Air Vehicle - (CAV) sticker. - https://www.bayareafastrak.org/en/guide/doINeedFlex.shtml - US_CO_EXPRESSTOLL (23): - CO, USA. - US_CO_GO_PASS (24): - CO, USA. - US_DE_EZPASSDE (25): - DE, USA. - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS (65): - FL, USA. - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD (66): - FL, USA. - US_FL_EPASS (67): - FL, USA. - US_FL_GIBA_TOLL_PASS (68): - FL, USA. - US_FL_LEEWAY (69): - FL, USA. - US_FL_SUNPASS (70): - FL, USA. - US_FL_SUNPASS_PRO (71): - FL, USA. - US_IL_EZPASSIL (73): - IL, USA. - US_IL_IPASS (72): - IL, USA. - US_IN_EZPASSIN (26): - IN, USA. - US_KS_BESTPASS_HORIZON (27): - KS, USA. - US_KS_KTAG (28): - KS, USA. - US_KS_NATIONALPASS (29): - KS, USA. - US_KS_PREPASS_ELITEPASS (30): - KS, USA. - US_KY_RIVERLINK (31): - KY, USA. - US_LA_GEAUXPASS (32): - LA, USA. - US_LA_TOLL_TAG (33): - LA, USA. - US_MA_EZPASSMA (6): - MA, USA. - US_MD_EZPASSMD (34): - MD, USA. - US_ME_EZPASSME (35): - ME, USA. - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): - MI, USA. - US_MI_BCPASS (94): - MI, USA. - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): - MI, USA. - US_MI_IQ_PROX_CARD (38): - MI, USA. - US_MI_MACKINAC_BRIDGE_MAC_PASS (39): - MI, USA. - US_MI_NEXPRESS_TOLL (40): - MI, USA. - US_MN_EZPASSMN (41): - MN, USA. - US_NC_EZPASSNC (42): - NC, USA. - US_NC_PEACH_PASS (87): - NC, USA. - US_NC_QUICK_PASS (43): - NC, USA. - US_NH_EZPASSNH (80): - NH, USA. - US_NJ_DOWNBEACH_EXPRESS_PASS (75): - NJ, USA. - US_NJ_EZPASSNJ (74): - NJ, USA. - US_NY_EXPRESSPASS (76): - NY, USA. - US_NY_EZPASSNY (77): - NY, USA. - US_OH_EZPASSOH (44): - OH, USA. - US_PA_EZPASSPA (45): - PA, USA. - US_RI_EZPASSRI (46): - RI, USA. - US_SC_PALPASS (47): - SC, USA. - US_TX_BANCPASS (48): - TX, USA. - US_TX_DEL_RIO_PASS (49): - TX, USA. - US_TX_EFAST_PASS (50): - TX, USA. - US_TX_EAGLE_PASS_EXPRESS_CARD (51): - TX, USA. - US_TX_EPTOLL (52): - TX, USA. - US_TX_EZ_CROSS (53): - TX, USA. - US_TX_EZTAG (54): - TX, USA. - US_TX_LAREDO_TRADE_TAG (55): - TX, USA. - US_TX_PLUSPASS (56): - TX, USA. - US_TX_TOLLTAG (57): - TX, USA. - US_TX_TXTAG (58): - TX, USA. - US_TX_XPRESS_CARD (59): - TX, USA. - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD (60): - UT, USA. - US_VA_EZPASSVA (61): - VA, USA. - US_WA_BREEZEBY (17): - WA, USA. - US_WA_GOOD_TO_GO (1): - WA, USA. - US_WV_EZPASSWV (62): - WV, USA. - US_WV_MEMORIAL_BRIDGE_TICKETS (63): - WV, USA. - US_WV_NEWELL_TOLL_BRIDGE_TICKET (64): - WV, USA. - """ - TOLL_PASS_UNSPECIFIED = 0 - AU_ETOLL_TAG = 82 - AU_EWAY_TAG = 83 - AU_LINKT = 2 - AR_TELEPASE = 3 - BR_AUTO_EXPRESO = 81 - BR_CONECTCAR = 7 - BR_MOVE_MAIS = 8 - BR_PASSA_RAPIDO = 88 - BR_SEM_PARAR = 9 - BR_TAGGY = 10 - BR_VELOE = 11 - CA_US_AKWASASNE_SEAWAY_CORPORATE_CARD = 84 - CA_US_AKWASASNE_SEAWAY_TRANSIT_CARD = 85 - CA_US_BLUE_WATER_EDGE_PASS = 18 - CA_US_CONNEXION = 19 - CA_US_NEXUS_CARD = 20 - ID_E_TOLL = 16 - IN_FASTAG = 78 - IN_LOCAL_HP_PLATE_EXEMPT = 79 - MX_IAVE = 90 - MX_PASE = 91 - MX_QUICKPASS = 93 - MX_SISTEMA_TELEPEAJE_CHIHUAHUA = 89 - MX_TAG_IAVE = 12 - MX_TAG_TELEVIA = 13 - MX_TELEVIA = 92 - MX_VIAPASS = 14 - US_AL_FREEDOM_PASS = 21 - US_AK_ANTON_ANDERSON_TUNNEL_BOOK_OF_10_TICKETS = 22 - US_CA_FASTRAK = 4 - US_CA_FASTRAK_CAV_STICKER = 86 - US_CO_EXPRESSTOLL = 23 - US_CO_GO_PASS = 24 - US_DE_EZPASSDE = 25 - US_FL_BOB_SIKES_TOLL_BRIDGE_PASS = 65 - US_FL_DUNES_COMMUNITY_DEVELOPMENT_DISTRICT_EXPRESSCARD = 66 - US_FL_EPASS = 67 - US_FL_GIBA_TOLL_PASS = 68 - US_FL_LEEWAY = 69 - US_FL_SUNPASS = 70 - US_FL_SUNPASS_PRO = 71 - US_IL_EZPASSIL = 73 - US_IL_IPASS = 72 - US_IN_EZPASSIN = 26 - US_KS_BESTPASS_HORIZON = 27 - US_KS_KTAG = 28 - US_KS_NATIONALPASS = 29 - US_KS_PREPASS_ELITEPASS = 30 - US_KY_RIVERLINK = 31 - US_LA_GEAUXPASS = 32 - US_LA_TOLL_TAG = 33 - US_MA_EZPASSMA = 6 - US_MD_EZPASSMD = 34 - US_ME_EZPASSME = 35 - US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 - US_MI_BCPASS = 94 - US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 - US_MI_IQ_PROX_CARD = 38 - US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 - US_MI_NEXPRESS_TOLL = 40 - US_MN_EZPASSMN = 41 - US_NC_EZPASSNC = 42 - US_NC_PEACH_PASS = 87 - US_NC_QUICK_PASS = 43 - US_NH_EZPASSNH = 80 - US_NJ_DOWNBEACH_EXPRESS_PASS = 75 - US_NJ_EZPASSNJ = 74 - US_NY_EXPRESSPASS = 76 - US_NY_EZPASSNY = 77 - US_OH_EZPASSOH = 44 - US_PA_EZPASSPA = 45 - US_RI_EZPASSRI = 46 - US_SC_PALPASS = 47 - US_TX_BANCPASS = 48 - US_TX_DEL_RIO_PASS = 49 - US_TX_EFAST_PASS = 50 - US_TX_EAGLE_PASS_EXPRESS_CARD = 51 - US_TX_EPTOLL = 52 - US_TX_EZ_CROSS = 53 - US_TX_EZTAG = 54 - US_TX_LAREDO_TRADE_TAG = 55 - US_TX_PLUSPASS = 56 - US_TX_TOLLTAG = 57 - US_TX_TXTAG = 58 - US_TX_XPRESS_CARD = 59 - US_UT_ADAMS_AVE_PARKWAY_EXPRESSCARD = 60 - US_VA_EZPASSVA = 61 - US_WA_BREEZEBY = 17 - US_WA_GOOD_TO_GO = 1 - US_WV_EZPASSWV = 62 - US_WV_MEMORIAL_BRIDGE_TICKETS = 63 - US_WV_NEWELL_TOLL_BRIDGE_TICKET = 64 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py deleted file mode 100644 index 93cfaf1ee04c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/units.py +++ /dev/null @@ -1,49 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Units', - }, -) - - -class Units(proto.Enum): - r"""A set of values that specify the unit of measure used in the - display. - - Values: - UNITS_UNSPECIFIED (0): - Units of measure not specified. Defaults to - the unit of measure inferred from the request. - METRIC (1): - Metric units of measure. - IMPERIAL (2): - Imperial (English) units of measure. - """ - UNITS_UNSPECIFIED = 0 - METRIC = 1 - IMPERIAL = 2 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py deleted file mode 100644 index faa6b5957eb3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_emission_type.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'VehicleEmissionType', - }, -) - - -class VehicleEmissionType(proto.Enum): - r"""A set of values describing the vehicle's emission type. Applies only - to the ``DRIVE`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. - - Values: - VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): - No emission type specified. Default to ``GASOLINE``. - GASOLINE (1): - Gasoline/petrol fueled vehicle. - ELECTRIC (2): - Electricity powered vehicle. - HYBRID (3): - Hybrid fuel (such as gasoline + electric) - vehicle. - DIESEL (4): - Diesel fueled vehicle. - """ - VEHICLE_EMISSION_TYPE_UNSPECIFIED = 0 - GASOLINE = 1 - ELECTRIC = 2 - HYBRID = 3 - DIESEL = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py deleted file mode 100644 index a2ad1ffd949e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import vehicle_emission_type - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'VehicleInfo', - }, -) - - -class VehicleInfo(proto.Message): - r"""Encapsulates the vehicle information, such as the license - plate last character. - - Attributes: - emission_type (google.maps.routing_v2.types.VehicleEmissionType): - Describes the vehicle's emission type. Applies only to the - ``DRIVE`` travel mode. - """ - - emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( - proto.ENUM, - number=2, - enum=vehicle_emission_type.VehicleEmissionType, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py deleted file mode 100644 index 71ae89e0e84f..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/waypoint.py +++ /dev/null @@ -1,126 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.routing_v2.types import location as gmr_location - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Waypoint', - }, -) - - -class Waypoint(proto.Message): - r"""Encapsulates a waypoint. Waypoints mark both the beginning - and end of a route, and include intermediate stops along the - route. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - location (google.maps.routing_v2.types.Location): - A point specified using geographic - coordinates, including an optional heading. - - This field is a member of `oneof`_ ``location_type``. - place_id (str): - The POI Place ID associated with the - waypoint. - - This field is a member of `oneof`_ ``location_type``. - address (str): - Human readable address or a plus code. - See https://plus.codes for details. - - This field is a member of `oneof`_ ``location_type``. - via (bool): - Marks this waypoint as a milestone rather a stopping point. - For each non-via waypoint in the request, the response - appends an entry to the - [legs][google.maps.routing.v2.Route.legs] array to provide - the details for stopovers on that leg of the trip. Set this - value to true when you want the route to pass through this - waypoint without stopping over. Via waypoints don't cause an - entry to be added to the ``legs`` array, but they do route - the journey through the waypoint. You can only set this - value on waypoints that are intermediates. The request fails - if you set this field on terminal waypoints. If - ``ComputeRoutesRequest.optimize_waypoint_order`` is set to - true then this field cannot be set to true; otherwise, the - request fails. - vehicle_stopover (bool): - Indicates that the waypoint is meant for vehicles to stop - at, where the intention is to either pickup or drop-off. - When you set this value, the calculated route won't include - non-\ ``via`` waypoints on roads that are unsuitable for - pickup and drop-off. This option works only for ``DRIVE`` - and ``TWO_WHEELER`` travel modes, and when the - ``location_type`` is - [Location][google.maps.routing.v2.Location]. - side_of_road (bool): - Indicates that the location of this waypoint is meant to - have a preference for the vehicle to stop at a particular - side of road. When you set this value, the route will pass - through the location so that the vehicle can stop at the - side of road that the location is biased towards from the - center of the road. This option works only for 'DRIVE' and - 'TWO_WHEELER' - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. - """ - - location: gmr_location.Location = proto.Field( - proto.MESSAGE, - number=1, - oneof='location_type', - message=gmr_location.Location, - ) - place_id: str = proto.Field( - proto.STRING, - number=2, - oneof='location_type', - ) - address: str = proto.Field( - proto.STRING, - number=7, - oneof='location_type', - ) - via: bool = proto.Field( - proto.BOOL, - number=3, - ) - vehicle_stopover: bool = proto.Field( - proto.BOOL, - number=4, - ) - side_of_road: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/mypy.ini b/owl-bot-staging/google-maps-routing/v2/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-maps-routing/v2/noxfile.py b/owl-bot-staging/google-maps-routing/v2/noxfile.py deleted file mode 100644 index 59757e684c85..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/routing_v2/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py deleted file mode 100644 index 381f53f7a26e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -async def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = await client.compute_route_matrix(request=request) - - # Handle the response - async for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py deleted file mode 100644 index 125691404b0b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_route_matrix_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRouteMatrix -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRouteMatrix_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -def sample_compute_route_matrix(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRouteMatrixRequest( - ) - - # Make the request - stream = client.compute_route_matrix(request=request) - - # Handle the response - for response in stream: - print(response) - -# [END routes_v2_generated_Routes_ComputeRouteMatrix_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py deleted file mode 100644 index c978c3e55cd7..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -async def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesAsyncClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = await client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_async] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py deleted file mode 100644 index ca13730e4ddc..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/routes_v2_generated_routes_compute_routes_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ComputeRoutes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-routing - - -# [START routes_v2_generated_Routes_ComputeRoutes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import routing_v2 - - -def sample_compute_routes(): - # Create a client - client = routing_v2.RoutesClient() - - # Initialize request argument(s) - request = routing_v2.ComputeRoutesRequest( - ) - - # Make the request - response = client.compute_routes(request=request) - - # Handle the response - print(response) - -# [END routes_v2_generated_Routes_ComputeRoutes_sync] diff --git a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json deleted file mode 100644 index b5ed5aca319c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json +++ /dev/null @@ -1,321 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.routing.v2", - "version": "v2" - } - ], - "language": "PYTHON", - "name": "google-maps-routing", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_route_matrix_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_route_matrix", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRouteMatrix", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRouteMatrix" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRouteMatrixRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "Iterable[google.maps.routing_v2.types.RouteMatrixElement]", - "shortName": "compute_route_matrix" - }, - "description": "Sample for ComputeRouteMatrix", - "file": "routes_v2_generated_routes_compute_route_matrix_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRouteMatrix_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_route_matrix_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.routing_v2.RoutesAsyncClient", - "shortName": "RoutesAsyncClient" - }, - "fullName": "google.maps.routing_v2.RoutesAsyncClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_routes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.routing_v2.RoutesClient", - "shortName": "RoutesClient" - }, - "fullName": "google.maps.routing_v2.RoutesClient.compute_routes", - "method": { - "fullName": "google.maps.routing.v2.Routes.ComputeRoutes", - "service": { - "fullName": "google.maps.routing.v2.Routes", - "shortName": "Routes" - }, - "shortName": "ComputeRoutes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.routing_v2.types.ComputeRoutesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.routing_v2.types.ComputeRoutesResponse", - "shortName": "compute_routes" - }, - "description": "Sample for ComputeRoutes", - "file": "routes_v2_generated_routes_compute_routes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "routes_v2_generated_Routes_ComputeRoutes_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "routes_v2_generated_routes_compute_routes_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py b/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py deleted file mode 100644 index ab8c9f6352a2..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/scripts/fixup_routing_v2_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class routingCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'language_code', 'region_code', 'extra_computations', ), - 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'region_code', 'units', 'requested_reference_routes', 'extra_computations', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=routingCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the routing client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-maps-routing/v2/setup.py b/owl-bot-staging/google-maps-routing/v2/setup.py deleted file mode 100644 index b93d9d947fd8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-maps-routing' - - -description = "Google Maps Routing API client library" - -version = {} -with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "google-geo-type >= 0.1.0, <1.0.0dev", -] -url = "https://github.com/googleapis/python-maps-routing" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.maps"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt deleted file mode 100644 index 33ac865954a6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 -google-geo-type==0.1.0 diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py deleted file mode 100644 index 231bc125017b..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py deleted file mode 100644 index 55f7b3a4ba31..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py +++ /dev/null @@ -1,1750 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.maps.routing_v2.services.routes import RoutesAsyncClient -from google.maps.routing_v2.services.routes import RoutesClient -from google.maps.routing_v2.services.routes import transports -from google.maps.routing_v2.types import fallback_info -from google.maps.routing_v2.types import geocoding_results -from google.maps.routing_v2.types import location -from google.maps.routing_v2.types import polyline -from google.maps.routing_v2.types import route -from google.maps.routing_v2.types import route_modifiers -from google.maps.routing_v2.types import route_travel_mode -from google.maps.routing_v2.types import routes_service -from google.maps.routing_v2.types import routing_preference -from google.maps.routing_v2.types import toll_passes -from google.maps.routing_v2.types import units -from google.maps.routing_v2.types import vehicle_emission_type -from google.maps.routing_v2.types import vehicle_info -from google.maps.routing_v2.types import waypoint -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -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 RoutesClient._get_default_mtls_endpoint(None) is None - assert RoutesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RoutesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RoutesGrpcTransport, "grpc"), - (transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RoutesRestTransport, "rest"), -]) -def test_routes_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RoutesClient, "grpc"), - (RoutesAsyncClient, "grpc_asyncio"), - (RoutesClient, "rest"), -]) -def test_routes_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://routes.googleapis.com' - ) - - -def test_routes_client_get_transport_class(): - transport = RoutesClient.get_transport_class() - available_transports = [ - transports.RoutesGrpcTransport, - transports.RoutesRestTransport, - ] - assert transport in available_transports - - transport = RoutesClient.get_transport_class("grpc") - assert transport == transports.RoutesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -def test_routes_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(RoutesClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "true"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RoutesClient, transports.RoutesGrpcTransport, "grpc", "false"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RoutesClient, transports.RoutesRestTransport, "rest", "true"), - (RoutesClient, transports.RoutesRestTransport, "rest", "false"), -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_routes_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - RoutesClient, RoutesAsyncClient -]) -@mock.patch.object(RoutesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RoutesAsyncClient)) -def test_routes_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc"), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio"), - (RoutesClient, transports.RoutesRestTransport, "rest"), -]) -def test_routes_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - 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, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RoutesClient, transports.RoutesRestTransport, "rest", None), -]) -def test_routes_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_routes_client_client_options_from_dict(): - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RoutesClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RoutesClient, transports.RoutesGrpcTransport, "grpc", grpc_helpers), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_routes_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "routes.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( -), - scopes=None, - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes(request_type, transport: str = 'grpc'): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = routes_service.ComputeRoutesResponse( - ) - response = client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - client.compute_routes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - -@pytest.mark.asyncio -async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(routes_service.ComputeRoutesResponse( - )) - response = await client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -@pytest.mark.asyncio -async def test_compute_routes_async_from_dict(): - await test_compute_routes_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix(request_type, transport: str = 'grpc'): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iter([routes_service.RouteMatrixElement()]) - response = client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, routes_service.RouteMatrixElement) - - -def test_compute_route_matrix_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - client.compute_route_matrix() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - -@pytest.mark.asyncio -async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock(side_effect=[routes_service.RouteMatrixElement()]) - response = await client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest() - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, routes_service.RouteMatrixElement) - - -@pytest.mark.asyncio -async def test_compute_route_matrix_async_from_dict(): - await test_compute_route_matrix_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes_rest(request_type): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = routes_service.ComputeRoutesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.compute_routes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_rest_required_fields(request_type=routes_service.ComputeRoutesRequest): - transport_class = transports.RoutesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_routes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.ComputeRoutesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.compute_routes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_routes_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_routes._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origin", "destination", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_routes_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_routes") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_routes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRoutesRequest.pb(routes_service.ComputeRoutesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) - - request = routes_service.ComputeRoutesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.ComputeRoutesResponse() - - client.compute_routes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compute_routes_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRoutesRequest): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.compute_routes(request) - - -def test_compute_routes_rest_error(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix_rest(request_type): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = routes_service.RouteMatrixElement( - origin_index=1279, - destination_index=1817, - condition=routes_service.RouteMatrixElementCondition.ROUTE_EXISTS, - distance_meters=1594, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - json_return_value = "[{}]".format(json_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.compute_route_matrix(request) - - assert isinstance(response, Iterable) - response = next(response) - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.RouteMatrixElement) - assert response.origin_index == 1279 - assert response.destination_index == 1817 - assert response.condition == routes_service.RouteMatrixElementCondition.ROUTE_EXISTS - assert response.distance_meters == 1594 - - -def test_compute_route_matrix_rest_required_fields(request_type=routes_service.ComputeRouteMatrixRequest): - transport_class = transports.RoutesRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).compute_route_matrix._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = routes_service.RouteMatrixElement() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - json_return_value = "[{}]".format(json_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - with mock.patch.object(response_value, 'iter_content') as iter_content: - iter_content.return_value = iter(json_return_value) - response = client.compute_route_matrix(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_compute_route_matrix_rest_unset_required_fields(): - transport = transports.RoutesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.compute_route_matrix._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("origins", "destinations", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_compute_route_matrix_rest_interceptors(null_interceptor): - transport = transports.RoutesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutesRestInterceptor(), - ) - client = RoutesClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RoutesRestInterceptor, "post_compute_route_matrix") as post, \ - mock.patch.object(transports.RoutesRestInterceptor, "pre_compute_route_matrix") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = routes_service.ComputeRouteMatrixRequest.pb(routes_service.ComputeRouteMatrixRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) - req.return_value._content = "[{}]".format(req.return_value._content) - - request = routes_service.ComputeRouteMatrixRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = routes_service.RouteMatrixElement() - - client.compute_route_matrix(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_compute_route_matrix_rest_bad_request(transport: str = 'rest', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.compute_route_matrix(request) - - -def test_compute_route_matrix_rest_error(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutesClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RoutesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RoutesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = RoutesClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RoutesGrpcTransport, - ) - -def test_routes_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_routes_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RoutesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'compute_routes', - 'compute_route_matrix', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_routes_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( -), - quota_project_id="octopus", - ) - - -def test_routes_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.maps.routing_v2.services.routes.transports.RoutesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RoutesTransport() - adc.assert_called_once() - - -def test_routes_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - RoutesClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - ], -) -def test_routes_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=(), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutesGrpcTransport, - transports.RoutesGrpcAsyncIOTransport, - transports.RoutesRestTransport, - ], -) -def test_routes_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.RoutesGrpcTransport, grpc_helpers), - (transports.RoutesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_routes_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "routes.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( -), - scopes=["1", "2"], - default_host="routes.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_routes_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.RoutesRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_routes_host_no_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_routes_host_with_port(transport_name): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='routes.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'routes.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://routes.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_routes_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RoutesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RoutesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.compute_routes._session - session2 = client2.transport.compute_routes._session - assert session1 != session2 - session1 = client1.transport.compute_route_matrix._session - session2 = client2.transport.compute_route_matrix._session - assert session1 != session2 -def test_routes_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_routes_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RoutesGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - 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 - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - 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=cred, - credentials_file=None, - scopes=None, - 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 - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RoutesGrpcTransport, transports.RoutesGrpcAsyncIOTransport]) -def test_routes_transport_channel_mtls_with_adc( - transport_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), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - 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 - - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RoutesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = RoutesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = RoutesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = RoutesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RoutesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = RoutesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = RoutesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = RoutesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RoutesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = RoutesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RoutesClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RoutesTransport, '_prep_wrapped_messages') as prep: - transport_class = RoutesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = RoutesAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (RoutesClient, transports.RoutesGrpcTransport), - (RoutesAsyncClient, transports.RoutesGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py b/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py index 057086111010..428909da9cff 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py @@ -58,11 +58,13 @@ class FallbackRoutingMode(proto.Enum): FALLBACK_ROUTING_MODE_UNSPECIFIED (0): Not used. FALLBACK_TRAFFIC_UNAWARE (1): - Indicates the "TRAFFIC_UNAWARE" routing mode was used to + Indicates the ``TRAFFIC_UNAWARE`` + [google.maps.routing.v2.RoutingPreference] was used to compute the response. FALLBACK_TRAFFIC_AWARE (2): - Indicates the "TRAFFIC_AWARE" routing mode was used to - compute the response. + Indicates the ``TRAFFIC_AWARE`` + [RoutingPreference][google.maps.routing.v2.RoutingPreference] + was used to compute the response. """ FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 FALLBACK_TRAFFIC_UNAWARE = 1 diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py b/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py index 24a07165a904..3aadb7121661 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py @@ -30,8 +30,10 @@ class GeocodingResults(proto.Message): - r"""Contains GeocodedWaypoints for origin, destination and - intermediate waypoints. Only populated for address waypoints. + r"""Contains + [GeocodedWaypoints][google.maps.routing.v2.GeocodedWaypoint] for + origin, destination and intermediate waypoints. Only populated for + address waypoints. Attributes: origin (google.maps.routing_v2.types.GeocodedWaypoint): diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/location.py b/packages/google-maps-routing/google/maps/routing_v2/types/location.py index 66cd5246a744..f3803ba2507f 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/location.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/location.py @@ -42,7 +42,8 @@ class Location(proto.Message): the road to use for pickup and drop-off. Heading values can be from 0 to 360, where 0 specifies a heading of due North, 90 specifies a heading of due East, etc. You can use this - field only for ``DRIVE`` and ``TWO_WHEELER`` travel modes. + field only for ``DRIVE`` and ``TWO_WHEELER`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. """ lat_lng: latlng_pb2.LatLng = proto.Field( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route.py b/packages/google-maps-routing/google/maps/routing_v2/types/route.py index b53dbf1fc163..0e4969057f71 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route.py @@ -54,10 +54,11 @@ class Route(proto.Message): legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): A collection of legs (path segments between waypoints) that make-up the route. Each leg corresponds to the trip between - two non-\ ``via`` Waypoints. For example, a route with no - intermediate waypoints has only one leg. A route that - includes one non-\ ``via`` intermediate waypoint has two - legs. A route that includes one ``via`` intermediate + two non-\ ``via`` + [Waypoints][google.maps.routing.v2.Waypoint]. For example, a + route with no intermediate waypoints has only one leg. A + route that includes one non-\ ``via`` intermediate waypoint + has two legs. A route that includes one ``via`` intermediate waypoint has one leg. The order of the legs matches the order of Waypoints from ``origin`` to ``intermediates`` to ``destination``. @@ -349,7 +350,8 @@ class RouteLeg(proto.Message): class RouteLegStep(proto.Message): - r"""Encapsulates a segment of a ``RouteLeg``. A step corresponds to a + r"""Encapsulates a segment of a + [RouteLeg][google.maps.routing.v2.RouteLeg]. A step corresponds to a single navigation instruction. Route legs are made up of steps. Attributes: diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py b/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py index 2ad524de7d31..21f0b175bd31 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py @@ -28,8 +28,9 @@ class RouteLabel(proto.Enum): - r"""Labels for the ``Route`` that are useful to identify specific - properties of the route to compare against others. + r"""Labels for the [Route][google.maps.routing.v2.Route] that are useful + to identify specific properties of the route to compare against + others. Values: ROUTE_LABEL_UNSPECIFIED (0): @@ -40,8 +41,8 @@ class RouteLabel(proto.Enum): DEFAULT_ROUTE_ALTERNATE (2): An alternative to the default "best" route. Routes like this will be returned when - ``ComputeRoutesRequest.compute_alternative_routes`` is - specified. + [compute_alternative_routes][google.maps.routing.v2.ComputeRoutesRequest.compute_alternative_routes] + is specified. FUEL_EFFICIENT (3): Fuel efficient route. Routes labeled with this value are determined to be optimized for diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py b/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py index a850f89669ef..8d3c62be2560 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py @@ -39,22 +39,22 @@ class RouteModifiers(proto.Message): Specifies whether to avoid toll roads where reasonable. Preference will be given to routes not containing toll roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - travel modes. + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. avoid_highways (bool): Specifies whether to avoid highways where reasonable. Preference will be given to routes not containing highways. - Applies only to the ``DRIVE`` and ``TWO_WHEELER`` travel - modes. + Applies only to the ``DRIVE`` and ``TWO_WHEELER`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. avoid_ferries (bool): Specifies whether to avoid ferries where reasonable. Preference will be given to routes not containing travel by ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` - travel modes. + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. avoid_indoor (bool): Specifies whether to avoid navigating indoors where reasonable. Preference will be given to routes not containing indoor navigation. Applies only to the ``WALK`` - travel mode. + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. vehicle_info (google.maps.routing_v2.types.VehicleInfo): Specifies the vehicle information. toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): @@ -62,7 +62,8 @@ class RouteModifiers(proto.Message): are provided, the API tries to return the pass price. If toll passes are not provided, the API treats the toll pass as unknown and tries to return the cash price. Applies only - to the DRIVE and TWO_WHEELER travel modes. + to the ``DRIVE`` and ``TWO_WHEELER`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. """ avoid_tolls: bool = proto.Field( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py b/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py index 7a5337a311f6..9a4109a9e795 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py @@ -28,11 +28,11 @@ class RouteTravelMode(proto.Enum): - r"""A set of values used to specify the mode of travel. NOTE: WALK, - BICYCLE, and TWO_WHEELER routes are in beta and might sometimes be - missing clear sidewalks, pedestrian paths, or bicycling paths. You - must display this warning to the user for all walking, bicycling, - and two-wheel routes that you display in your app. + r"""A set of values used to specify the mode of travel. NOTE: ``WALK``, + ``BICYCLE``, and ``TWO_WHEELER`` routes are in beta and might + sometimes be missing clear sidewalks, pedestrian paths, or bicycling + paths. You must display this warning to the user for all walking, + bicycling, and two-wheel routes that you display in your app. Values: TRAVEL_MODE_UNSPECIFIED (0): diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py index cec054a68b9d..81f18bab8136 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py @@ -123,16 +123,17 @@ class ComputeRoutesRequest(proto.Message): units (google.maps.routing_v2.types.Units): Optional. Specifies the units of measure for the display fields. This includes the ``instruction`` field in - ``NavigationInstruction``. The units of measure used for the - route, leg, step distance, and duration are not affected by - this value. If you don't provide this value, then the - display units are inferred from the location of the request. + [NavigationInstruction][google.maps.routing.v2.NavigationInstruction]. + The units of measure used for the route, leg, step distance, + and duration are not affected by this value. If you don't + provide this value, then the display units are inferred from + the location of the request. requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): Optional. Specifies what reference routes to calculate as part of the request in addition to the default route. A reference route is a route with a different route - calculation objective than the default route. For example an - FUEL_EFFICIENT reference route calculation takes into + calculation objective than the default route. For example a + ``FUEL_EFFICIENT`` reference route calculation takes into account various parameters that would generate an optimal fuel efficient route. extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): @@ -468,11 +469,13 @@ class RouteMatrixElement(proto.Message): The travel distance of the route, in meters. duration (google.protobuf.duration_pb2.Duration): The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. + the + [routing_preference][google.maps.routing.v2.ComputeRouteMatrixRequest.routing_preference] + to ``TRAFFIC_UNAWARE``, then this value is the same as + ``static_duration``. If you set the ``routing_preference`` + to either ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``, + then this value is calculated taking traffic conditions into + account. static_duration (google.protobuf.duration_pb2.Duration): The duration of traveling through the route without taking traffic conditions into diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py b/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py index f93bdcda32c0..26fb06d13c32 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py @@ -39,13 +39,15 @@ class RoutingPreference(proto.Enum): Computes routes without taking live traffic conditions into consideration. Suitable when traffic conditions don't matter or are not applicable. Using this value produces the lowest - latency. Note: For ``RouteTravelMode`` DRIVE and TWO_WHEELER - choice of route and duration are based on road network and - average time-independent traffic conditions. Results for a - given request may vary over time due to changes in the road - network, updated average traffic conditions, and the - distributed nature of the service. Results may also vary - between nearly-equivalent routes at any time or frequency. + latency. Note: For + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] + ``DRIVE`` and ``TWO_WHEELER`` choice of route and duration + are based on road network and average time-independent + traffic conditions. Results for a given request may vary + over time due to changes in the road network, updated + average traffic conditions, and the distributed nature of + the service. Results may also vary between nearly-equivalent + routes at any time or frequency. TRAFFIC_AWARE (2): Calculates routes taking live traffic conditions into consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py b/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py index ffd0f8a21a62..238811a3522f 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py @@ -49,6 +49,8 @@ class SpeedReadingInterval(proto.Message): This field is a member of `oneof`_ ``_end_polyline_point_index``. speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): Traffic speed in this interval. + + This field is a member of `oneof`_ ``speed_type``. """ class Speed(proto.Enum): @@ -82,6 +84,7 @@ class Speed(proto.Enum): speed: Speed = proto.Field( proto.ENUM, number=3, + oneof="speed_type", enum=Speed, ) diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py b/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py index 87048e6140b2..901f8ea51f8a 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py @@ -29,19 +29,20 @@ class TollInfo(proto.Message): - r"""Encapsulates toll information on a ``Route`` or on a ``RouteLeg``. + r"""Encapsulates toll information on a + [Route][google.maps.routing.v2.Route] or on a + [RouteLeg][google.maps.routing.v2.RouteLeg]. Attributes: estimated_price (MutableSequence[google.type.money_pb2.Money]): - The monetary amount of tolls for the - corresponding Route or RouteLeg. This list - contains a money amount for each currency that - is expected to be charged by the toll stations. - Typically this list will contain only one item - for routes with tolls in one currency. For - international trips, this list may contain - multiple items to reflect tolls in different - currencies. + The monetary amount of tolls for the corresponding + [Route][google.maps.routing.v2.Route] or + [RouteLeg][google.maps.routing.v2.RouteLeg]. This list + contains a money amount for each currency that is expected + to be charged by the toll stations. Typically this list will + contain only one item for routes with tolls in one currency. + For international trips, this list may contain multiple + items to reflect tolls in different currencies. """ estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py b/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py index 4832e675cd62..6ca198eb924c 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py @@ -177,6 +177,8 @@ class TollPass(proto.Enum): ME, USA. US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): MI, USA. + US_MI_BCPASS (94): + MI, USA. US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): MI, USA. US_MI_IQ_PROX_CARD (38): @@ -306,6 +308,7 @@ class TollPass(proto.Enum): US_MD_EZPASSMD = 34 US_ME_EZPASSME = 35 US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 + US_MI_BCPASS = 94 US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 US_MI_IQ_PROX_CARD = 38 US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py index 442c8524a860..0df563e53a46 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py @@ -28,13 +28,13 @@ class VehicleEmissionType(proto.Enum): - r"""A set of values describing the vehicle's emission type. - Applies only to the DRIVE travel mode. + r"""A set of values describing the vehicle's emission type. Applies only + to the ``DRIVE`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. Values: VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): - No emission type specified. Default to - GASOLINE. + No emission type specified. Default to ``GASOLINE``. GASOLINE (1): Gasoline/petrol fueled vehicle. ELECTRIC (2): diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py index da1f14271dca..4005a547d2eb 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py @@ -35,8 +35,8 @@ class VehicleInfo(proto.Message): Attributes: emission_type (google.maps.routing_v2.types.VehicleEmissionType): - Describes the vehicle's emission type. - Applies only to the DRIVE travel mode. + Describes the vehicle's emission type. Applies only to the + ``DRIVE`` travel mode. """ emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py b/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py index 0b8158d4c5ff..0b9160d1c2e0 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py @@ -60,8 +60,9 @@ class Waypoint(proto.Message): via (bool): Marks this waypoint as a milestone rather a stopping point. For each non-via waypoint in the request, the response - appends an entry to the ``legs`` array to provide the - details for stopovers on that leg of the trip. Set this + appends an entry to the + [legs][google.maps.routing.v2.Route.legs] array to provide + the details for stopovers on that leg of the trip. Set this value to true when you want the route to pass through this waypoint without stopping over. Via waypoints don't cause an entry to be added to the ``legs`` array, but they do route @@ -78,7 +79,8 @@ class Waypoint(proto.Message): non-\ ``via`` waypoints on roads that are unsuitable for pickup and drop-off. This option works only for ``DRIVE`` and ``TWO_WHEELER`` travel modes, and when the - ``location_type`` is ``location``. + ``location_type`` is + [Location][google.maps.routing.v2.Location]. side_of_road (bool): Indicates that the location of this waypoint is meant to have a preference for the vehicle to stop at a particular @@ -86,7 +88,8 @@ class Waypoint(proto.Message): through the location so that the vehicle can stop at the side of road that the location is biased towards from the center of the road. This option works only for 'DRIVE' and - 'TWO_WHEELER' travel modes. + 'TWO_WHEELER' + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. """ location: gmr_location.Location = proto.Field( From f0d22a653425a9462a24afc0a8b2c67eec61ad43 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Fri, 24 Mar 2023 14:07:22 +0000 Subject: [PATCH 11/12] Fix build. The issue will be fixed upstream in cl/516494358 --- .../maps/routing_v2/types/fallback_info.py | 8 ++- .../routing_v2/types/geocoding_results.py | 6 +-- .../google/maps/routing_v2/types/location.py | 3 +- .../google/maps/routing_v2/types/route.py | 18 +++---- .../maps/routing_v2/types/route_label.py | 9 ++-- .../maps/routing_v2/types/route_modifiers.py | 13 +++-- .../routing_v2/types/route_travel_mode.py | 10 ++-- .../maps/routing_v2/types/routes_service.py | 54 ++++--------------- .../routing_v2/types/routing_preference.py | 16 +++--- .../types/speed_reading_interval.py | 3 -- .../google/maps/routing_v2/types/toll_info.py | 21 ++++---- .../maps/routing_v2/types/toll_passes.py | 3 -- .../routing_v2/types/vehicle_emission_type.py | 8 +-- .../maps/routing_v2/types/vehicle_info.py | 4 +- .../google/maps/routing_v2/types/waypoint.py | 11 ++-- .../scripts/fixup_routing_v2_keywords.py | 4 +- 16 files changed, 69 insertions(+), 122 deletions(-) diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py b/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py index 428909da9cff..057086111010 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py @@ -58,13 +58,11 @@ class FallbackRoutingMode(proto.Enum): FALLBACK_ROUTING_MODE_UNSPECIFIED (0): Not used. FALLBACK_TRAFFIC_UNAWARE (1): - Indicates the ``TRAFFIC_UNAWARE`` - [google.maps.routing.v2.RoutingPreference] was used to + Indicates the "TRAFFIC_UNAWARE" routing mode was used to compute the response. FALLBACK_TRAFFIC_AWARE (2): - Indicates the ``TRAFFIC_AWARE`` - [RoutingPreference][google.maps.routing.v2.RoutingPreference] - was used to compute the response. + Indicates the "TRAFFIC_AWARE" routing mode was used to + compute the response. """ FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 FALLBACK_TRAFFIC_UNAWARE = 1 diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py b/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py index 3aadb7121661..24a07165a904 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py @@ -30,10 +30,8 @@ class GeocodingResults(proto.Message): - r"""Contains - [GeocodedWaypoints][google.maps.routing.v2.GeocodedWaypoint] for - origin, destination and intermediate waypoints. Only populated for - address waypoints. + r"""Contains GeocodedWaypoints for origin, destination and + intermediate waypoints. Only populated for address waypoints. Attributes: origin (google.maps.routing_v2.types.GeocodedWaypoint): diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/location.py b/packages/google-maps-routing/google/maps/routing_v2/types/location.py index f3803ba2507f..66cd5246a744 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/location.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/location.py @@ -42,8 +42,7 @@ class Location(proto.Message): the road to use for pickup and drop-off. Heading values can be from 0 to 360, where 0 specifies a heading of due North, 90 specifies a heading of due East, etc. You can use this - field only for ``DRIVE`` and ``TWO_WHEELER`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + field only for ``DRIVE`` and ``TWO_WHEELER`` travel modes. """ lat_lng: latlng_pb2.LatLng = proto.Field( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route.py b/packages/google-maps-routing/google/maps/routing_v2/types/route.py index 0e4969057f71..44ab9630a649 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route.py @@ -17,7 +17,7 @@ from typing import MutableMapping, MutableSequence -from google.geo.type import viewport_pb2 # type: ignore +from google.geo.type.types import viewport as ggt_viewport from google.protobuf import duration_pb2 # type: ignore import proto # type: ignore @@ -54,11 +54,10 @@ class Route(proto.Message): legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): A collection of legs (path segments between waypoints) that make-up the route. Each leg corresponds to the trip between - two non-\ ``via`` - [Waypoints][google.maps.routing.v2.Waypoint]. For example, a - route with no intermediate waypoints has only one leg. A - route that includes one non-\ ``via`` intermediate waypoint - has two legs. A route that includes one ``via`` intermediate + two non-\ ``via`` Waypoints. For example, a route with no + intermediate waypoints has only one leg. A route that + includes one non-\ ``via`` intermediate waypoint has two + legs. A route that includes one ``via`` intermediate waypoint has one leg. The order of the legs matches the order of Waypoints from ``origin`` to ``intermediates`` to ``destination``. @@ -138,10 +137,10 @@ class Route(proto.Message): proto.STRING, number=7, ) - viewport: viewport_pb2.Viewport = proto.Field( + viewport: ggt_viewport.Viewport = proto.Field( proto.MESSAGE, number=8, - message=viewport_pb2.Viewport, + message=ggt_viewport.Viewport, ) travel_advisory: "RouteTravelAdvisory" = proto.Field( proto.MESSAGE, @@ -350,8 +349,7 @@ class RouteLeg(proto.Message): class RouteLegStep(proto.Message): - r"""Encapsulates a segment of a - [RouteLeg][google.maps.routing.v2.RouteLeg]. A step corresponds to a + r"""Encapsulates a segment of a ``RouteLeg``. A step corresponds to a single navigation instruction. Route legs are made up of steps. Attributes: diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py b/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py index 21f0b175bd31..2ad524de7d31 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py @@ -28,9 +28,8 @@ class RouteLabel(proto.Enum): - r"""Labels for the [Route][google.maps.routing.v2.Route] that are useful - to identify specific properties of the route to compare against - others. + r"""Labels for the ``Route`` that are useful to identify specific + properties of the route to compare against others. Values: ROUTE_LABEL_UNSPECIFIED (0): @@ -41,8 +40,8 @@ class RouteLabel(proto.Enum): DEFAULT_ROUTE_ALTERNATE (2): An alternative to the default "best" route. Routes like this will be returned when - [compute_alternative_routes][google.maps.routing.v2.ComputeRoutesRequest.compute_alternative_routes] - is specified. + ``ComputeRoutesRequest.compute_alternative_routes`` is + specified. FUEL_EFFICIENT (3): Fuel efficient route. Routes labeled with this value are determined to be optimized for diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py b/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py index 8d3c62be2560..a850f89669ef 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py @@ -39,22 +39,22 @@ class RouteModifiers(proto.Message): Specifies whether to avoid toll roads where reasonable. Preference will be given to routes not containing toll roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + travel modes. avoid_highways (bool): Specifies whether to avoid highways where reasonable. Preference will be given to routes not containing highways. - Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + Applies only to the ``DRIVE`` and ``TWO_WHEELER`` travel + modes. avoid_ferries (bool): Specifies whether to avoid ferries where reasonable. Preference will be given to routes not containing travel by ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + travel modes. avoid_indoor (bool): Specifies whether to avoid navigating indoors where reasonable. Preference will be given to routes not containing indoor navigation. Applies only to the ``WALK`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + travel mode. vehicle_info (google.maps.routing_v2.types.VehicleInfo): Specifies the vehicle information. toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): @@ -62,8 +62,7 @@ class RouteModifiers(proto.Message): are provided, the API tries to return the pass price. If toll passes are not provided, the API treats the toll pass as unknown and tries to return the cash price. Applies only - to the ``DRIVE`` and ``TWO_WHEELER`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + to the DRIVE and TWO_WHEELER travel modes. """ avoid_tolls: bool = proto.Field( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py b/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py index 9a4109a9e795..7a5337a311f6 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py @@ -28,11 +28,11 @@ class RouteTravelMode(proto.Enum): - r"""A set of values used to specify the mode of travel. NOTE: ``WALK``, - ``BICYCLE``, and ``TWO_WHEELER`` routes are in beta and might - sometimes be missing clear sidewalks, pedestrian paths, or bicycling - paths. You must display this warning to the user for all walking, - bicycling, and two-wheel routes that you display in your app. + r"""A set of values used to specify the mode of travel. NOTE: WALK, + BICYCLE, and TWO_WHEELER routes are in beta and might sometimes be + missing clear sidewalks, pedestrian paths, or bicycling paths. You + must display this warning to the user for all walking, bicycling, + and two-wheel routes that you display in your app. Values: TRAVEL_MODE_UNSPECIFIED (0): diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py index 81f18bab8136..8324d3b000e0 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py @@ -116,24 +116,19 @@ class ComputeRoutesRequest(proto.Message): for the list of supported languages. When you don't provide this value, the display language is inferred from the location of the route request. - region_code (str): - Optional. The region code, specified as a ccTLD ("top-level - domain") two-character value. For more information see - https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains units (google.maps.routing_v2.types.Units): Optional. Specifies the units of measure for the display fields. This includes the ``instruction`` field in - [NavigationInstruction][google.maps.routing.v2.NavigationInstruction]. - The units of measure used for the route, leg, step distance, - and duration are not affected by this value. If you don't - provide this value, then the display units are inferred from - the location of the request. + ``NavigationInstruction``. The units of measure used for the + route, leg, step distance, and duration are not affected by + this value. If you don't provide this value, then the + display units are inferred from the location of the request. requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): Optional. Specifies what reference routes to calculate as part of the request in addition to the default route. A reference route is a route with a different route - calculation objective than the default route. For example a - ``FUEL_EFFICIENT`` reference route calculation takes into + calculation objective than the default route. For example an + FUEL_EFFICIENT reference route calculation takes into account various parameters that would generate an optimal fuel efficient route. extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): @@ -232,10 +227,6 @@ class ExtraComputation(proto.Enum): proto.STRING, number=10, ) - region_code: str = proto.Field( - proto.STRING, - number=16, - ) units: gmr_units.Units = proto.Field( proto.ENUM, number=11, @@ -328,19 +319,6 @@ class ComputeRouteMatrixRequest(proto.Message): you made the request. If you set this value to a time that has already occurred, the request fails. - language_code (str): - Optional. The BCP-47 language code, such as "en-US" or - "sr-Latn". For more information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - See `Language - Support `__ - for the list of supported languages. When you don't provide - this value, the display language is inferred from the - location of the first origin. - region_code (str): - Optional. The region code, specified as a ccTLD ("top-level - domain") two-character value. For more information see - https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): Optional. A list of extra computations which may be used to complete the request. Note: These @@ -388,14 +366,6 @@ class ExtraComputation(proto.Enum): number=5, message=timestamp_pb2.Timestamp, ) - language_code: str = proto.Field( - proto.STRING, - number=6, - ) - region_code: str = proto.Field( - proto.STRING, - number=9, - ) extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( proto.ENUM, number=8, @@ -469,13 +439,11 @@ class RouteMatrixElement(proto.Message): The travel distance of the route, in meters. duration (google.protobuf.duration_pb2.Duration): The length of time needed to navigate the route. If you set - the - [routing_preference][google.maps.routing.v2.ComputeRouteMatrixRequest.routing_preference] - to ``TRAFFIC_UNAWARE``, then this value is the same as - ``static_duration``. If you set the ``routing_preference`` - to either ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``, - then this value is calculated taking traffic conditions into - account. + the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this + value is the same as ``static_duration``. If you set the + ``routing_preference`` to either ``TRAFFIC_AWARE`` or + ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated + taking traffic conditions into account. static_duration (google.protobuf.duration_pb2.Duration): The duration of traveling through the route without taking traffic conditions into diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py b/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py index 26fb06d13c32..f93bdcda32c0 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py @@ -39,15 +39,13 @@ class RoutingPreference(proto.Enum): Computes routes without taking live traffic conditions into consideration. Suitable when traffic conditions don't matter or are not applicable. Using this value produces the lowest - latency. Note: For - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] - ``DRIVE`` and ``TWO_WHEELER`` choice of route and duration - are based on road network and average time-independent - traffic conditions. Results for a given request may vary - over time due to changes in the road network, updated - average traffic conditions, and the distributed nature of - the service. Results may also vary between nearly-equivalent - routes at any time or frequency. + latency. Note: For ``RouteTravelMode`` DRIVE and TWO_WHEELER + choice of route and duration are based on road network and + average time-independent traffic conditions. Results for a + given request may vary over time due to changes in the road + network, updated average traffic conditions, and the + distributed nature of the service. Results may also vary + between nearly-equivalent routes at any time or frequency. TRAFFIC_AWARE (2): Calculates routes taking live traffic conditions into consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py b/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py index 238811a3522f..ffd0f8a21a62 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py @@ -49,8 +49,6 @@ class SpeedReadingInterval(proto.Message): This field is a member of `oneof`_ ``_end_polyline_point_index``. speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): Traffic speed in this interval. - - This field is a member of `oneof`_ ``speed_type``. """ class Speed(proto.Enum): @@ -84,7 +82,6 @@ class Speed(proto.Enum): speed: Speed = proto.Field( proto.ENUM, number=3, - oneof="speed_type", enum=Speed, ) diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py b/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py index 901f8ea51f8a..87048e6140b2 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py @@ -29,20 +29,19 @@ class TollInfo(proto.Message): - r"""Encapsulates toll information on a - [Route][google.maps.routing.v2.Route] or on a - [RouteLeg][google.maps.routing.v2.RouteLeg]. + r"""Encapsulates toll information on a ``Route`` or on a ``RouteLeg``. Attributes: estimated_price (MutableSequence[google.type.money_pb2.Money]): - The monetary amount of tolls for the corresponding - [Route][google.maps.routing.v2.Route] or - [RouteLeg][google.maps.routing.v2.RouteLeg]. This list - contains a money amount for each currency that is expected - to be charged by the toll stations. Typically this list will - contain only one item for routes with tolls in one currency. - For international trips, this list may contain multiple - items to reflect tolls in different currencies. + The monetary amount of tolls for the + corresponding Route or RouteLeg. This list + contains a money amount for each currency that + is expected to be charged by the toll stations. + Typically this list will contain only one item + for routes with tolls in one currency. For + international trips, this list may contain + multiple items to reflect tolls in different + currencies. """ estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py b/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py index 6ca198eb924c..4832e675cd62 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py @@ -177,8 +177,6 @@ class TollPass(proto.Enum): ME, USA. US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): MI, USA. - US_MI_BCPASS (94): - MI, USA. US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): MI, USA. US_MI_IQ_PROX_CARD (38): @@ -308,7 +306,6 @@ class TollPass(proto.Enum): US_MD_EZPASSMD = 34 US_ME_EZPASSME = 35 US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 - US_MI_BCPASS = 94 US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 US_MI_IQ_PROX_CARD = 38 US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py index 0df563e53a46..442c8524a860 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py @@ -28,13 +28,13 @@ class VehicleEmissionType(proto.Enum): - r"""A set of values describing the vehicle's emission type. Applies only - to the ``DRIVE`` - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + r"""A set of values describing the vehicle's emission type. + Applies only to the DRIVE travel mode. Values: VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): - No emission type specified. Default to ``GASOLINE``. + No emission type specified. Default to + GASOLINE. GASOLINE (1): Gasoline/petrol fueled vehicle. ELECTRIC (2): diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py index 4005a547d2eb..da1f14271dca 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py @@ -35,8 +35,8 @@ class VehicleInfo(proto.Message): Attributes: emission_type (google.maps.routing_v2.types.VehicleEmissionType): - Describes the vehicle's emission type. Applies only to the - ``DRIVE`` travel mode. + Describes the vehicle's emission type. + Applies only to the DRIVE travel mode. """ emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py b/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py index 0b9160d1c2e0..0b8158d4c5ff 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py @@ -60,9 +60,8 @@ class Waypoint(proto.Message): via (bool): Marks this waypoint as a milestone rather a stopping point. For each non-via waypoint in the request, the response - appends an entry to the - [legs][google.maps.routing.v2.Route.legs] array to provide - the details for stopovers on that leg of the trip. Set this + appends an entry to the ``legs`` array to provide the + details for stopovers on that leg of the trip. Set this value to true when you want the route to pass through this waypoint without stopping over. Via waypoints don't cause an entry to be added to the ``legs`` array, but they do route @@ -79,8 +78,7 @@ class Waypoint(proto.Message): non-\ ``via`` waypoints on roads that are unsuitable for pickup and drop-off. This option works only for ``DRIVE`` and ``TWO_WHEELER`` travel modes, and when the - ``location_type`` is - [Location][google.maps.routing.v2.Location]. + ``location_type`` is ``location``. side_of_road (bool): Indicates that the location of this waypoint is meant to have a preference for the vehicle to stop at a particular @@ -88,8 +86,7 @@ class Waypoint(proto.Message): through the location so that the vehicle can stop at the side of road that the location is biased towards from the center of the road. This option works only for 'DRIVE' and - 'TWO_WHEELER' - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. + 'TWO_WHEELER' travel modes. """ location: gmr_location.Location = proto.Field( diff --git a/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py b/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py index ab8c9f6352a2..291c4ea93db5 100644 --- a/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py +++ b/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py @@ -39,8 +39,8 @@ def partition( class routingCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'language_code', 'region_code', 'extra_computations', ), - 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'region_code', 'units', 'requested_reference_routes', 'extra_computations', ), + 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'extra_computations', ), + 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'units', 'requested_reference_routes', 'extra_computations', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: From 5fd905784c35262c8a72e78f714ee911370300d3 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Fri, 24 Mar 2023 14:22:21 +0000 Subject: [PATCH 12/12] Fix build. The issue will be fixed upstream in cl/516494358 --- .../maps/routing_v2/types/fallback_info.py | 8 +-- .../routing_v2/types/geocoding_results.py | 6 ++- .../google/maps/routing_v2/types/location.py | 3 +- .../google/maps/routing_v2/types/route.py | 14 ++--- .../maps/routing_v2/types/route_label.py | 9 ++-- .../maps/routing_v2/types/route_modifiers.py | 13 ++--- .../routing_v2/types/route_travel_mode.py | 10 ++-- .../maps/routing_v2/types/routes_service.py | 54 +++++++++++++++---- .../routing_v2/types/routing_preference.py | 16 +++--- .../types/speed_reading_interval.py | 3 ++ .../google/maps/routing_v2/types/toll_info.py | 21 ++++---- .../maps/routing_v2/types/toll_passes.py | 3 ++ .../routing_v2/types/vehicle_emission_type.py | 8 +-- .../maps/routing_v2/types/vehicle_info.py | 4 +- .../google/maps/routing_v2/types/waypoint.py | 11 ++-- .../scripts/fixup_routing_v2_keywords.py | 4 +- 16 files changed, 120 insertions(+), 67 deletions(-) diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py b/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py index 057086111010..428909da9cff 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/fallback_info.py @@ -58,11 +58,13 @@ class FallbackRoutingMode(proto.Enum): FALLBACK_ROUTING_MODE_UNSPECIFIED (0): Not used. FALLBACK_TRAFFIC_UNAWARE (1): - Indicates the "TRAFFIC_UNAWARE" routing mode was used to + Indicates the ``TRAFFIC_UNAWARE`` + [google.maps.routing.v2.RoutingPreference] was used to compute the response. FALLBACK_TRAFFIC_AWARE (2): - Indicates the "TRAFFIC_AWARE" routing mode was used to - compute the response. + Indicates the ``TRAFFIC_AWARE`` + [RoutingPreference][google.maps.routing.v2.RoutingPreference] + was used to compute the response. """ FALLBACK_ROUTING_MODE_UNSPECIFIED = 0 FALLBACK_TRAFFIC_UNAWARE = 1 diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py b/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py index 24a07165a904..3aadb7121661 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/geocoding_results.py @@ -30,8 +30,10 @@ class GeocodingResults(proto.Message): - r"""Contains GeocodedWaypoints for origin, destination and - intermediate waypoints. Only populated for address waypoints. + r"""Contains + [GeocodedWaypoints][google.maps.routing.v2.GeocodedWaypoint] for + origin, destination and intermediate waypoints. Only populated for + address waypoints. Attributes: origin (google.maps.routing_v2.types.GeocodedWaypoint): diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/location.py b/packages/google-maps-routing/google/maps/routing_v2/types/location.py index 66cd5246a744..f3803ba2507f 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/location.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/location.py @@ -42,7 +42,8 @@ class Location(proto.Message): the road to use for pickup and drop-off. Heading values can be from 0 to 360, where 0 specifies a heading of due North, 90 specifies a heading of due East, etc. You can use this - field only for ``DRIVE`` and ``TWO_WHEELER`` travel modes. + field only for ``DRIVE`` and ``TWO_WHEELER`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. """ lat_lng: latlng_pb2.LatLng = proto.Field( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route.py b/packages/google-maps-routing/google/maps/routing_v2/types/route.py index 44ab9630a649..c1272b02a875 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route.py @@ -54,10 +54,11 @@ class Route(proto.Message): legs (MutableSequence[google.maps.routing_v2.types.RouteLeg]): A collection of legs (path segments between waypoints) that make-up the route. Each leg corresponds to the trip between - two non-\ ``via`` Waypoints. For example, a route with no - intermediate waypoints has only one leg. A route that - includes one non-\ ``via`` intermediate waypoint has two - legs. A route that includes one ``via`` intermediate + two non-\ ``via`` + [Waypoints][google.maps.routing.v2.Waypoint]. For example, a + route with no intermediate waypoints has only one leg. A + route that includes one non-\ ``via`` intermediate waypoint + has two legs. A route that includes one ``via`` intermediate waypoint has one leg. The order of the legs matches the order of Waypoints from ``origin`` to ``intermediates`` to ``destination``. @@ -82,7 +83,7 @@ class Route(proto.Message): warnings (MutableSequence[str]): An array of warnings to show when displaying the route. - viewport (google.geo.type.viewport_pb2.Viewport): + viewport (google.geo.type.types.Viewport): The viewport bounding box of the polyline. travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): Additional information about the route. @@ -349,7 +350,8 @@ class RouteLeg(proto.Message): class RouteLegStep(proto.Message): - r"""Encapsulates a segment of a ``RouteLeg``. A step corresponds to a + r"""Encapsulates a segment of a + [RouteLeg][google.maps.routing.v2.RouteLeg]. A step corresponds to a single navigation instruction. Route legs are made up of steps. Attributes: diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py b/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py index 2ad524de7d31..21f0b175bd31 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route_label.py @@ -28,8 +28,9 @@ class RouteLabel(proto.Enum): - r"""Labels for the ``Route`` that are useful to identify specific - properties of the route to compare against others. + r"""Labels for the [Route][google.maps.routing.v2.Route] that are useful + to identify specific properties of the route to compare against + others. Values: ROUTE_LABEL_UNSPECIFIED (0): @@ -40,8 +41,8 @@ class RouteLabel(proto.Enum): DEFAULT_ROUTE_ALTERNATE (2): An alternative to the default "best" route. Routes like this will be returned when - ``ComputeRoutesRequest.compute_alternative_routes`` is - specified. + [compute_alternative_routes][google.maps.routing.v2.ComputeRoutesRequest.compute_alternative_routes] + is specified. FUEL_EFFICIENT (3): Fuel efficient route. Routes labeled with this value are determined to be optimized for diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py b/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py index a850f89669ef..8d3c62be2560 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route_modifiers.py @@ -39,22 +39,22 @@ class RouteModifiers(proto.Message): Specifies whether to avoid toll roads where reasonable. Preference will be given to routes not containing toll roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - travel modes. + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. avoid_highways (bool): Specifies whether to avoid highways where reasonable. Preference will be given to routes not containing highways. - Applies only to the ``DRIVE`` and ``TWO_WHEELER`` travel - modes. + Applies only to the ``DRIVE`` and ``TWO_WHEELER`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. avoid_ferries (bool): Specifies whether to avoid ferries where reasonable. Preference will be given to routes not containing travel by ferries. Applies only to the ``DRIVE`` and\ ``TWO_WHEELER`` - travel modes. + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. avoid_indoor (bool): Specifies whether to avoid navigating indoors where reasonable. Preference will be given to routes not containing indoor navigation. Applies only to the ``WALK`` - travel mode. + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. vehicle_info (google.maps.routing_v2.types.VehicleInfo): Specifies the vehicle information. toll_passes (MutableSequence[google.maps.routing_v2.types.TollPass]): @@ -62,7 +62,8 @@ class RouteModifiers(proto.Message): are provided, the API tries to return the pass price. If toll passes are not provided, the API treats the toll pass as unknown and tries to return the cash price. Applies only - to the DRIVE and TWO_WHEELER travel modes. + to the ``DRIVE`` and ``TWO_WHEELER`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. """ avoid_tolls: bool = proto.Field( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py b/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py index 7a5337a311f6..9a4109a9e795 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/route_travel_mode.py @@ -28,11 +28,11 @@ class RouteTravelMode(proto.Enum): - r"""A set of values used to specify the mode of travel. NOTE: WALK, - BICYCLE, and TWO_WHEELER routes are in beta and might sometimes be - missing clear sidewalks, pedestrian paths, or bicycling paths. You - must display this warning to the user for all walking, bicycling, - and two-wheel routes that you display in your app. + r"""A set of values used to specify the mode of travel. NOTE: ``WALK``, + ``BICYCLE``, and ``TWO_WHEELER`` routes are in beta and might + sometimes be missing clear sidewalks, pedestrian paths, or bicycling + paths. You must display this warning to the user for all walking, + bicycling, and two-wheel routes that you display in your app. Values: TRAVEL_MODE_UNSPECIFIED (0): diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py index 8324d3b000e0..81f18bab8136 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/routes_service.py @@ -116,19 +116,24 @@ class ComputeRoutesRequest(proto.Message): for the list of supported languages. When you don't provide this value, the display language is inferred from the location of the route request. + region_code (str): + Optional. The region code, specified as a ccTLD ("top-level + domain") two-character value. For more information see + https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains units (google.maps.routing_v2.types.Units): Optional. Specifies the units of measure for the display fields. This includes the ``instruction`` field in - ``NavigationInstruction``. The units of measure used for the - route, leg, step distance, and duration are not affected by - this value. If you don't provide this value, then the - display units are inferred from the location of the request. + [NavigationInstruction][google.maps.routing.v2.NavigationInstruction]. + The units of measure used for the route, leg, step distance, + and duration are not affected by this value. If you don't + provide this value, then the display units are inferred from + the location of the request. requested_reference_routes (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ReferenceRoute]): Optional. Specifies what reference routes to calculate as part of the request in addition to the default route. A reference route is a route with a different route - calculation objective than the default route. For example an - FUEL_EFFICIENT reference route calculation takes into + calculation objective than the default route. For example a + ``FUEL_EFFICIENT`` reference route calculation takes into account various parameters that would generate an optimal fuel efficient route. extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRoutesRequest.ExtraComputation]): @@ -227,6 +232,10 @@ class ExtraComputation(proto.Enum): proto.STRING, number=10, ) + region_code: str = proto.Field( + proto.STRING, + number=16, + ) units: gmr_units.Units = proto.Field( proto.ENUM, number=11, @@ -319,6 +328,19 @@ class ComputeRouteMatrixRequest(proto.Message): you made the request. If you set this value to a time that has already occurred, the request fails. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + See `Language + Support `__ + for the list of supported languages. When you don't provide + this value, the display language is inferred from the + location of the first origin. + region_code (str): + Optional. The region code, specified as a ccTLD ("top-level + domain") two-character value. For more information see + https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains extra_computations (MutableSequence[google.maps.routing_v2.types.ComputeRouteMatrixRequest.ExtraComputation]): Optional. A list of extra computations which may be used to complete the request. Note: These @@ -366,6 +388,14 @@ class ExtraComputation(proto.Enum): number=5, message=timestamp_pb2.Timestamp, ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + region_code: str = proto.Field( + proto.STRING, + number=9, + ) extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( proto.ENUM, number=8, @@ -439,11 +469,13 @@ class RouteMatrixElement(proto.Message): The travel distance of the route, in meters. duration (google.protobuf.duration_pb2.Duration): The length of time needed to navigate the route. If you set - the ``routing_preference`` to ``TRAFFIC_UNAWARE``, then this - value is the same as ``static_duration``. If you set the - ``routing_preference`` to either ``TRAFFIC_AWARE`` or - ``TRAFFIC_AWARE_OPTIMAL``, then this value is calculated - taking traffic conditions into account. + the + [routing_preference][google.maps.routing.v2.ComputeRouteMatrixRequest.routing_preference] + to ``TRAFFIC_UNAWARE``, then this value is the same as + ``static_duration``. If you set the ``routing_preference`` + to either ``TRAFFIC_AWARE`` or ``TRAFFIC_AWARE_OPTIMAL``, + then this value is calculated taking traffic conditions into + account. static_duration (google.protobuf.duration_pb2.Duration): The duration of traveling through the route without taking traffic conditions into diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py b/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py index f93bdcda32c0..26fb06d13c32 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/routing_preference.py @@ -39,13 +39,15 @@ class RoutingPreference(proto.Enum): Computes routes without taking live traffic conditions into consideration. Suitable when traffic conditions don't matter or are not applicable. Using this value produces the lowest - latency. Note: For ``RouteTravelMode`` DRIVE and TWO_WHEELER - choice of route and duration are based on road network and - average time-independent traffic conditions. Results for a - given request may vary over time due to changes in the road - network, updated average traffic conditions, and the - distributed nature of the service. Results may also vary - between nearly-equivalent routes at any time or frequency. + latency. Note: For + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] + ``DRIVE`` and ``TWO_WHEELER`` choice of route and duration + are based on road network and average time-independent + traffic conditions. Results for a given request may vary + over time due to changes in the road network, updated + average traffic conditions, and the distributed nature of + the service. Results may also vary between nearly-equivalent + routes at any time or frequency. TRAFFIC_AWARE (2): Calculates routes taking live traffic conditions into consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py b/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py index ffd0f8a21a62..238811a3522f 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/speed_reading_interval.py @@ -49,6 +49,8 @@ class SpeedReadingInterval(proto.Message): This field is a member of `oneof`_ ``_end_polyline_point_index``. speed (google.maps.routing_v2.types.SpeedReadingInterval.Speed): Traffic speed in this interval. + + This field is a member of `oneof`_ ``speed_type``. """ class Speed(proto.Enum): @@ -82,6 +84,7 @@ class Speed(proto.Enum): speed: Speed = proto.Field( proto.ENUM, number=3, + oneof="speed_type", enum=Speed, ) diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py b/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py index 87048e6140b2..901f8ea51f8a 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/toll_info.py @@ -29,19 +29,20 @@ class TollInfo(proto.Message): - r"""Encapsulates toll information on a ``Route`` or on a ``RouteLeg``. + r"""Encapsulates toll information on a + [Route][google.maps.routing.v2.Route] or on a + [RouteLeg][google.maps.routing.v2.RouteLeg]. Attributes: estimated_price (MutableSequence[google.type.money_pb2.Money]): - The monetary amount of tolls for the - corresponding Route or RouteLeg. This list - contains a money amount for each currency that - is expected to be charged by the toll stations. - Typically this list will contain only one item - for routes with tolls in one currency. For - international trips, this list may contain - multiple items to reflect tolls in different - currencies. + The monetary amount of tolls for the corresponding + [Route][google.maps.routing.v2.Route] or + [RouteLeg][google.maps.routing.v2.RouteLeg]. This list + contains a money amount for each currency that is expected + to be charged by the toll stations. Typically this list will + contain only one item for routes with tolls in one currency. + For international trips, this list may contain multiple + items to reflect tolls in different currencies. """ estimated_price: MutableSequence[money_pb2.Money] = proto.RepeatedField( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py b/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py index 4832e675cd62..6ca198eb924c 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/toll_passes.py @@ -177,6 +177,8 @@ class TollPass(proto.Enum): ME, USA. US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD (36): MI, USA. + US_MI_BCPASS (94): + MI, USA. US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG (37): MI, USA. US_MI_IQ_PROX_CARD (38): @@ -306,6 +308,7 @@ class TollPass(proto.Enum): US_MD_EZPASSMD = 34 US_ME_EZPASSME = 35 US_MI_AMBASSADOR_BRIDGE_PREMIER_COMMUTER_CARD = 36 + US_MI_BCPASS = 94 US_MI_GROSSE_ILE_TOLL_BRIDGE_PASS_TAG = 37 US_MI_IQ_PROX_CARD = 38 US_MI_MACKINAC_BRIDGE_MAC_PASS = 39 diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py index 442c8524a860..0df563e53a46 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_emission_type.py @@ -28,13 +28,13 @@ class VehicleEmissionType(proto.Enum): - r"""A set of values describing the vehicle's emission type. - Applies only to the DRIVE travel mode. + r"""A set of values describing the vehicle's emission type. Applies only + to the ``DRIVE`` + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. Values: VEHICLE_EMISSION_TYPE_UNSPECIFIED (0): - No emission type specified. Default to - GASOLINE. + No emission type specified. Default to ``GASOLINE``. GASOLINE (1): Gasoline/petrol fueled vehicle. ELECTRIC (2): diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py index da1f14271dca..4005a547d2eb 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/vehicle_info.py @@ -35,8 +35,8 @@ class VehicleInfo(proto.Message): Attributes: emission_type (google.maps.routing_v2.types.VehicleEmissionType): - Describes the vehicle's emission type. - Applies only to the DRIVE travel mode. + Describes the vehicle's emission type. Applies only to the + ``DRIVE`` travel mode. """ emission_type: vehicle_emission_type.VehicleEmissionType = proto.Field( diff --git a/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py b/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py index 0b8158d4c5ff..0b9160d1c2e0 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py +++ b/packages/google-maps-routing/google/maps/routing_v2/types/waypoint.py @@ -60,8 +60,9 @@ class Waypoint(proto.Message): via (bool): Marks this waypoint as a milestone rather a stopping point. For each non-via waypoint in the request, the response - appends an entry to the ``legs`` array to provide the - details for stopovers on that leg of the trip. Set this + appends an entry to the + [legs][google.maps.routing.v2.Route.legs] array to provide + the details for stopovers on that leg of the trip. Set this value to true when you want the route to pass through this waypoint without stopping over. Via waypoints don't cause an entry to be added to the ``legs`` array, but they do route @@ -78,7 +79,8 @@ class Waypoint(proto.Message): non-\ ``via`` waypoints on roads that are unsuitable for pickup and drop-off. This option works only for ``DRIVE`` and ``TWO_WHEELER`` travel modes, and when the - ``location_type`` is ``location``. + ``location_type`` is + [Location][google.maps.routing.v2.Location]. side_of_road (bool): Indicates that the location of this waypoint is meant to have a preference for the vehicle to stop at a particular @@ -86,7 +88,8 @@ class Waypoint(proto.Message): through the location so that the vehicle can stop at the side of road that the location is biased towards from the center of the road. This option works only for 'DRIVE' and - 'TWO_WHEELER' travel modes. + 'TWO_WHEELER' + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode]. """ location: gmr_location.Location = proto.Field( diff --git a/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py b/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py index 291c4ea93db5..ab8c9f6352a2 100644 --- a/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py +++ b/packages/google-maps-routing/scripts/fixup_routing_v2_keywords.py @@ -39,8 +39,8 @@ def partition( class routingCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'extra_computations', ), - 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'units', 'requested_reference_routes', 'extra_computations', ), + 'compute_route_matrix': ('origins', 'destinations', 'travel_mode', 'routing_preference', 'departure_time', 'language_code', 'region_code', 'extra_computations', ), + 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'region_code', 'units', 'requested_reference_routes', 'extra_computations', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: