From b13725761eb9fa184e68eb1073ccbddcc537c4da Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 26 Nov 2024 20:56:48 +0000 Subject: [PATCH 1/2] feat: add API for shorter distance reference routes PiperOrigin-RevId: 700387857 Source-Link: https://github.com/googleapis/googleapis/commit/4deb95d3bd31ed01524753dbdb94c2c52ce42103 Source-Link: https://github.com/googleapis/googleapis-gen/commit/a38a16c43c68681bbf5c0de7914b72790a4b6b2b Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcm91dGluZy8uT3dsQm90LnlhbWwiLCJoIjoiYTM4YTE2YzQzYzY4NjgxYmJmNWMwZGU3OTE0YjcyNzkwYTRiNmIyYiJ9 --- .../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 + .../v2/docs/_static/custom.css | 3 + .../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 | 113 + .../v2/google/maps/routing/gapic_version.py | 16 + .../v2/google/maps/routing/py.typed | 2 + .../v2/google/maps/routing_v2/__init__.py | 114 + .../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 | 460 ++++ .../maps/routing_v2/services/routes/client.py | 781 ++++++ .../services/routes/transports/README.rst | 9 + .../services/routes/transports/__init__.py | 38 + .../services/routes/transports/base.py | 167 ++ .../services/routes/transports/grpc.py | 369 +++ .../routes/transports/grpc_asyncio.py | 395 +++ .../services/routes/transports/rest.py | 384 +++ .../services/routes/transports/rest_base.py | 185 ++ .../google/maps/routing_v2/types/__init__.py | 150 ++ .../maps/routing_v2/types/fallback_info.py | 105 + .../routing_v2/types/geocoding_results.py | 127 + .../maps/routing_v2/types/localized_time.py | 58 + .../google/maps/routing_v2/types/location.py | 63 + .../google/maps/routing_v2/types/maneuver.py | 103 + .../types/navigation_instruction.py | 58 + .../google/maps/routing_v2/types/polyline.py | 113 + .../v2/google/maps/routing_v2/types/route.py | 790 ++++++ .../maps/routing_v2/types/route_label.py | 62 + .../maps/routing_v2/types/route_modifiers.py | 98 + .../routing_v2/types/route_travel_mode.py | 63 + .../maps/routing_v2/types/routes_service.py | 732 ++++++ .../routing_v2/types/routing_preference.py | 71 + .../types/speed_reading_interval.py | 92 + .../google/maps/routing_v2/types/toll_info.py | 57 + .../maps/routing_v2/types/toll_passes.py | 376 +++ .../maps/routing_v2/types/traffic_model.py | 64 + .../google/maps/routing_v2/types/transit.py | 259 ++ .../routing_v2/types/transit_preferences.py | 97 + .../v2/google/maps/routing_v2/types/units.py | 49 + .../routing_v2/types/vehicle_emission_type.py | 56 + .../maps/routing_v2/types/vehicle_info.py | 51 + .../google/maps/routing_v2/types/waypoint.py | 126 + .../google-maps-routing/v2/mypy.ini | 3 + .../google-maps-routing/v2/noxfile.py | 280 ++ ...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 | 99 + .../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.13.txt | 7 + .../v2/testing/constraints-3.7.txt | 11 + .../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 | 2328 +++++++++++++++++ 73 files changed, 10998 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/_static/custom.css 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/README.rst 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/services/routes/transports/rest_base.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/localized_time.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/traffic_model.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py create mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.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.13.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/_static/custom.css b/owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} 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..4b30f5a14b3e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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"2023, 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 = 'en' + +# 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..3a2d987095fc --- /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..6435ad0166ed --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.localized_time import LocalizedTime +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 RouteLegStepTransitDetails +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.traffic_model import TrafficModel +from google.maps.routing_v2.types.transit import TransitAgency +from google.maps.routing_v2.types.transit import TransitLine +from google.maps.routing_v2.types.transit import TransitStop +from google.maps.routing_v2.types.transit import TransitVehicle +from google.maps.routing_v2.types.transit_preferences import TransitPreferences +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', + 'LocalizedTime', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTransitDetails', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'TrafficModel', + 'TransitAgency', + 'TransitLine', + 'TransitStop', + 'TransitVehicle', + 'TransitPreferences', + '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..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.0.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..cdae66b5d7f6 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.localized_time import LocalizedTime +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 RouteLegStepTransitDetails +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.traffic_model import TrafficModel +from .types.transit import TransitAgency +from .types.transit import TransitLine +from .types.transit import TransitStop +from .types.transit import TransitVehicle +from .types.transit_preferences import TransitPreferences +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', +'LocalizedTime', +'Location', +'Maneuver', +'NavigationInstruction', +'Polyline', +'PolylineEncoding', +'PolylineQuality', +'Route', +'RouteLabel', +'RouteLeg', +'RouteLegStep', +'RouteLegStepTransitDetails', +'RouteLegStepTravelAdvisory', +'RouteLegTravelAdvisory', +'RouteMatrixDestination', +'RouteMatrixElement', +'RouteMatrixElementCondition', +'RouteMatrixOrigin', +'RouteModifiers', +'RouteTravelAdvisory', +'RouteTravelMode', +'RoutesClient', +'RoutingPreference', +'SpeedReadingInterval', +'TollInfo', +'TollPass', +'TrafficModel', +'TransitAgency', +'TransitLine', +'TransitPreferences', +'TransitStop', +'TransitVehicle', +'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..558c8aab67c5 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.0.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..8f6cf068242c --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..1d5f9c21bfea --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..3315c0768267 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py @@ -0,0 +1,460 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 re +from typing import Dict, Callable, 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_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # 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 + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = RoutesClient._DEFAULT_UNIVERSE + + 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 + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = RoutesClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RoutesTransport, Callable[..., RoutesTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the routes async 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 (Optional[Union[str,RoutesTransport,Callable[..., RoutesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RoutesTransport constructor. + 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. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + 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_async.AsyncRetry): 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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + 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._client._transport._wrapped_methods[self._client._transport.compute_routes] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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_async.AsyncRetry): 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]: + Contains 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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + 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._client._transport._wrapped_methods[self._client._transport.compute_route_matrix] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "RoutesAsyncClient": + 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..fcf4c589de2c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py @@ -0,0 +1,781 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast +import warnings + +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, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # 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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "routes.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "routes.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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): + """Deprecated. 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. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + 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 + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + 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`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = RoutesClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = RoutesClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = RoutesClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RoutesTransport, Callable[..., 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 (Optional[Union[str,RoutesTransport,Callable[..., RoutesTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RoutesTransport constructor. + 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. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = RoutesClient._read_environment_variables() + self._client_cert_source = RoutesClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = RoutesClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._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. + transport_provided = isinstance(transport, RoutesTransport) + if transport_provided: + # transport is a RoutesTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(RoutesTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + RoutesClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + 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_init: Union[Type[RoutesTransport], Callable[..., RoutesTransport]] = ( + RoutesClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RoutesTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + 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] + + # Validate the universe domain. + self._validate_universe_domain() + + # 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]: + Contains 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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + 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] + + # Validate the universe domain. + self._validate_universe_domain() + + # 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/README.rst b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst new file mode 100644 index 000000000000..ece3f327f1db --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RoutesTransport` is the ABC for all transports. +- public child `RoutesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RoutesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRoutesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RoutesRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). 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..cac74dd752a0 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..ecdfa6e5fcc0 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 (default: 'routes.googleapis.com'). + 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 not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + 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 + + @property + def host(self): + return self._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..223360b6ba76 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py @@ -0,0 +1,369 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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[Union[grpc.Channel, Callable[..., 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 (default: 'routes.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + 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 a ``channel`` instance 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 a ``channel`` instance 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 isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # 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: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + 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..e4752aeff4c2 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py @@ -0,0 +1,395 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 inspect +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.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +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`. + 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[Union[aio.Channel, Callable[..., 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 (default: 'routes.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + 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 a ``channel`` instance 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 a ``channel`` instance 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 isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # 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: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + 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._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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 _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.compute_routes: self._wrap_method( + self.compute_routes, + default_timeout=None, + client_info=client_info, + ), + self.compute_route_matrix: self._wrap_method( + self.compute_route_matrix, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__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..e62eb44c3f16 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +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 gapic_v1 + +from google.protobuf import json_format + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.maps.routing_v2.types import routes_service + + +from .rest_base import _BaseRoutesRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{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(_BaseRoutesRestTransport): + """REST backend synchronous 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 (default: 'routes.googleapis.com'). + 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 + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + 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(_BaseRoutesRestTransport._BaseComputeRouteMatrix, RoutesRestStub): + def __hash__(self): + return hash("RoutesRestTransport.ComputeRouteMatrix") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + stream=True, + ) + return response + + 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: + Contains route information computed + for an origin/destination pair in the + ComputeRouteMatrix API. This proto can + be streamed to the client. + + """ + + http_options = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_http_options() + request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) + transcoded_request = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_transcoded_request(http_options, request) + + body = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_query_params_json(transcoded_request) + + # Send the request + response = RoutesRestTransport._ComputeRouteMatrix._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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(_BaseRoutesRestTransport._BaseComputeRoutes, RoutesRestStub): + def __hash__(self): + return hash("RoutesRestTransport.ComputeRoutes") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + 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 = _BaseRoutesRestTransport._BaseComputeRoutes._get_http_options() + request, metadata = self._interceptor.pre_compute_routes(request, metadata) + transcoded_request = _BaseRoutesRestTransport._BaseComputeRoutes._get_transcoded_request(http_options, request) + + body = _BaseRoutesRestTransport._BaseComputeRoutes._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRoutesRestTransport._BaseComputeRoutes._get_query_params_json(transcoded_request) + + # Send the request + response = RoutesRestTransport._ComputeRoutes._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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/services/routes/transports/rest_base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py new file mode 100644 index 000000000000..89bf86170eeb --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from .base import RoutesTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.maps.routing_v2.types import routes_service + + +class _BaseRoutesRestTransport(RoutesTransport): + """Base REST backend transport for Routes. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + 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[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'routes.googleapis.com'). + credentials (Optional[Any]): 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. + 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 + 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 + ) + + class _BaseComputeRouteMatrix: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/distanceMatrix/v2:computeRouteMatrix', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseRoutesRestTransport._BaseComputeRouteMatrix._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseComputeRoutes: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __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} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/directions/v2:computeRoutes', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = routes_service.ComputeRoutesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseRoutesRestTransport._BaseComputeRoutes._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseRoutesRestTransport', +) 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..56fa2a5f9cbb --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 .localized_time import ( + LocalizedTime, +) +from .location import ( + Location, +) +from .maneuver import ( + Maneuver, +) +from .navigation_instruction import ( + NavigationInstruction, +) +from .polyline import ( + Polyline, + PolylineEncoding, + PolylineQuality, +) +from .route import ( + Route, + RouteLeg, + RouteLegStep, + RouteLegStepTransitDetails, + RouteLegStepTravelAdvisory, + RouteLegTravelAdvisory, + RouteTravelAdvisory, +) +from .route_label import ( + RouteLabel, +) +from .route_modifiers import ( + RouteModifiers, +) +from .route_travel_mode import ( + RouteTravelMode, +) +from .routes_service import ( + ComputeRouteMatrixRequest, + ComputeRoutesRequest, + ComputeRoutesResponse, + RouteMatrixDestination, + RouteMatrixElement, + RouteMatrixOrigin, + RouteMatrixElementCondition, +) +from .routing_preference import ( + RoutingPreference, +) +from .speed_reading_interval import ( + SpeedReadingInterval, +) +from .toll_info import ( + TollInfo, +) +from .toll_passes import ( + TollPass, +) +from .traffic_model import ( + TrafficModel, +) +from .transit import ( + TransitAgency, + TransitLine, + TransitStop, + TransitVehicle, +) +from .transit_preferences import ( + TransitPreferences, +) +from .units import ( + Units, +) +from .vehicle_emission_type import ( + VehicleEmissionType, +) +from .vehicle_info import ( + VehicleInfo, +) +from .waypoint import ( + Waypoint, +) + +__all__ = ( + 'FallbackInfo', + 'FallbackReason', + 'FallbackRoutingMode', + 'GeocodedWaypoint', + 'GeocodingResults', + 'LocalizedTime', + 'Location', + 'Maneuver', + 'NavigationInstruction', + 'Polyline', + 'PolylineEncoding', + 'PolylineQuality', + 'Route', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTransitDetails', + 'RouteLegStepTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteTravelAdvisory', + 'RouteLabel', + 'RouteModifiers', + 'RouteTravelMode', + 'ComputeRouteMatrixRequest', + 'ComputeRoutesRequest', + 'ComputeRoutesResponse', + 'RouteMatrixDestination', + 'RouteMatrixElement', + 'RouteMatrixOrigin', + 'RouteMatrixElementCondition', + 'RoutingPreference', + 'SpeedReadingInterval', + 'TollInfo', + 'TollPass', + 'TrafficModel', + 'TransitAgency', + 'TransitLine', + 'TransitStop', + 'TransitVehicle', + 'TransitPreferences', + '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..e9c371f86902 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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`` + [``RoutingPreference``][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..e7b5ac69343c --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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: `Address types and address component + 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/localized_time.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py new file mode 100644 index 000000000000..cd33d5012b85 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 localized_text_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'LocalizedTime', + }, +) + + +class LocalizedTime(proto.Message): + r"""Localized description of time. + + Attributes: + time (google.type.localized_text_pb2.LocalizedText): + The time specified as a string in a given + time zone. + time_zone (str): + Contains the time zone. The value is the name of the time + zone as defined in the `IANA Time Zone + Database `__, e.g. + "America/New_York". + """ + + time: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + time_zone: 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/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py new file mode 100644 index 000000000000..895301cea20d --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 specifies the side of the road + 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, and so on. 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..e8275813708a --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 (for example, turn left, merge, or + straight). + + 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. + DEPART (19): + Initial maneuver. + NAME_CHANGE (20): + Used to indicate a street name change. + """ + 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 + DEPART = 19 + NAME_CHANGE = 20 + + +__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..f9a930014166 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 (for example, turn left, merge, + or straight). 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..fe776cd21e8b --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..a79f0977ae74 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py @@ -0,0 +1,790 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.types import viewport as ggt_viewport +from google.maps.routing_v2.types import localized_time +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 route_travel_mode +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.maps.routing_v2.types import transit +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import localized_text_pb2 # type: ignore +from google.type import money_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'Route', + 'RouteTravelAdvisory', + 'RouteLegTravelAdvisory', + 'RouteLegStepTravelAdvisory', + 'RouteLeg', + 'RouteLegStep', + 'RouteLegStepTransitDetails', + }, +) + + +class Route(proto.Message): + r"""Contains 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 travel through the route + without taking traffic conditions into + consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall route polyline. This polyline is 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.types.Viewport): + The viewport bounding box of the polyline. + travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): + Additional information about the route. + optimized_intermediate_waypoint_index (MutableSequence[int]): + If you set + [``optimize_waypoint_order``][google.maps.routing.v2.ComputeRoutesRequest.optimize_waypoint_order] + to true, this field contains the optimized ordering of + intermediate waypoints. Otherwise, this field is empty. For + example, if you give an input of Origin: LA; Intermediate + waypoints: Dallas, Bangor, Phoenix; Destination: New York; + and the optimized intermediate waypoint order is Phoenix, + Dallas, Bangor, then this field contains the values [2, 0, + 1]. The index starts with 0 for the first intermediate + waypoint provided in the input. + localized_values (google.maps.routing_v2.types.Route.RouteLocalizedValues): + Text representations of properties of the ``Route``. + route_token (str): + An opaque token that can be passed to `Navigation + SDK `__ + to reconstruct the route during navigation, and, in the + event of rerouting, honor the original intention when the + route was created. Treat this token as an opaque blob. Don't + compare its value across requests as its value may change + even if the service returns the exact same route. + + 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 not supported for requests that + have Via waypoints. + """ + + class RouteLocalizedValues(proto.Message): + r"""Text representations of certain properties. + + Attributes: + distance (google.type.localized_text_pb2.LocalizedText): + Travel distance represented in text form. + duration (google.type.localized_text_pb2.LocalizedText): + Duration, represented in text form and localized to the + region of the query. Takes traffic conditions into + consideration. Note: If you did not request traffic + information, this value is the same value as + ``static_duration``. + static_duration (google.type.localized_text_pb2.LocalizedText): + Duration without taking traffic conditions + into consideration, represented in text form. + transit_fare (google.type.localized_text_pb2.LocalizedText): + Transit fare represented in text form. + """ + + distance: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=2, + message=localized_text_pb2.LocalizedText, + ) + static_duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=3, + message=localized_text_pb2.LocalizedText, + ) + transit_fare: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=4, + message=localized_text_pb2.LocalizedText, + ) + + 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: ggt_viewport.Viewport = proto.Field( + proto.MESSAGE, + number=8, + message=ggt_viewport.Viewport, + ) + travel_advisory: 'RouteTravelAdvisory' = proto.Field( + proto.MESSAGE, + number=9, + message='RouteTravelAdvisory', + ) + optimized_intermediate_waypoint_index: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=10, + ) + localized_values: RouteLocalizedValues = proto.Field( + proto.MESSAGE, + number=11, + message=RouteLocalizedValues, + ) + route_token: str = proto.Field( + proto.STRING, + number=12, + ) + + +class RouteTravelAdvisory(proto.Message): + r"""Contains the additional information that the user should be + informed about, such as possible traffic zone restrictions. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Contains information about tolls on the route. This field is + only populated if tolls are expected on the route. If this + field is set, but the ``estimatedPrice`` subfield is not + populated, then the route contains tolls, but the estimated + price is unknown. If this field is not set, then there are + no tolls expected 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 predicted fuel consumption in + microliters. + route_restrictions_partially_ignored (bool): + Returned route may have restrictions that are + not suitable for requested travel mode or route + modifiers. + transit_fare (google.type.money_pb2.Money): + If present, contains the total fare or ticket costs on this + route This property is only returned for ``TRANSIT`` + requests and only for routes where fare information is + available for all transit steps. + """ + + 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, + ) + route_restrictions_partially_ignored: bool = proto.Field( + proto.BOOL, + number=6, + ) + transit_fare: money_pb2.Money = proto.Field( + proto.MESSAGE, + number=7, + message=money_pb2.Money, + ) + + +class RouteLegTravelAdvisory(proto.Message): + r"""Contains the additional information that the user should be + informed about on a leg step, such as possible traffic zone + restrictions. + + Attributes: + toll_info (google.maps.routing_v2.types.TollInfo): + Contains 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 ``RouteLeg`` 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"""Contains the additional information that the user should be + informed about, such as possible traffic zone restrictions 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"""Contains 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 travel through the leg, + calculated without taking traffic conditions + into consideration. + polyline (google.maps.routing_v2.types.Polyline): + The overall polyline for this leg that includes each + ``step``'s polyline. + start_location (google.maps.routing_v2.types.Location): + The start location of this leg. This location 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 location 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): + Contains the additional information that the + user should be informed about, such as possible + traffic zone restrictions, on a route leg. + localized_values (google.maps.routing_v2.types.RouteLeg.RouteLegLocalizedValues): + Text representations of properties of the ``RouteLeg``. + steps_overview (google.maps.routing_v2.types.RouteLeg.StepsOverview): + Overview information about the steps in this ``RouteLeg``. + This field is only populated for TRANSIT routes. + """ + + class RouteLegLocalizedValues(proto.Message): + r"""Text representations of certain properties. + + Attributes: + distance (google.type.localized_text_pb2.LocalizedText): + Travel distance represented in text form. + duration (google.type.localized_text_pb2.LocalizedText): + Duration, represented in text form and localized to the + region of the query. Takes traffic conditions into + consideration. Note: If you did not request traffic + information, this value is the same value as + static_duration. + static_duration (google.type.localized_text_pb2.LocalizedText): + Duration without taking traffic conditions + into consideration, represented in text form. + """ + + distance: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=2, + message=localized_text_pb2.LocalizedText, + ) + static_duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=3, + message=localized_text_pb2.LocalizedText, + ) + + class StepsOverview(proto.Message): + r"""Provides overview information about a list of ``RouteLegStep``\ s. + + Attributes: + multi_modal_segments (MutableSequence[google.maps.routing_v2.types.RouteLeg.StepsOverview.MultiModalSegment]): + Summarized information about different multi-modal segments + of the ``RouteLeg.steps``. This field is not populated if + the ``RouteLeg`` does not contain any multi-modal segments + in the steps. + """ + + class MultiModalSegment(proto.Message): + r"""Provides summarized information about different multi-modal segments + of the ``RouteLeg.steps``. A multi-modal segment is defined as one + or more contiguous ``RouteLegStep`` that have the same + ``RouteTravelMode``. This field is not populated if the ``RouteLeg`` + does not contain any multi-modal segments in the steps. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + step_start_index (int): + The corresponding ``RouteLegStep`` index that is the start + of a multi-modal segment. + + This field is a member of `oneof`_ ``_step_start_index``. + step_end_index (int): + The corresponding ``RouteLegStep`` index that is the end of + a multi-modal segment. + + This field is a member of `oneof`_ ``_step_end_index``. + navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): + NavigationInstruction for the multi-modal + segment. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + The travel mode of the multi-modal segment. + """ + + step_start_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + step_end_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( + proto.MESSAGE, + number=3, + message=gmr_navigation_instruction.NavigationInstruction, + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=4, + enum=route_travel_mode.RouteTravelMode, + ) + + multi_modal_segments: MutableSequence['RouteLeg.StepsOverview.MultiModalSegment'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RouteLeg.StepsOverview.MultiModalSegment', + ) + + 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', + ) + localized_values: RouteLegLocalizedValues = proto.Field( + proto.MESSAGE, + number=9, + message=RouteLegLocalizedValues, + ) + steps_overview: StepsOverview = proto.Field( + proto.MESSAGE, + number=10, + message=StepsOverview, + ) + + +class RouteLegStep(proto.Message): + r"""Contains 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): + Contains the additional information that the + user should be informed about, such as possible + traffic zone restrictions, on a leg step. + localized_values (google.maps.routing_v2.types.RouteLegStep.RouteLegStepLocalizedValues): + Text representations of properties of the ``RouteLegStep``. + transit_details (google.maps.routing_v2.types.RouteLegStepTransitDetails): + Details pertaining to this step if the travel mode is + ``TRANSIT``. + travel_mode (google.maps.routing_v2.types.RouteTravelMode): + The travel mode used for this step. + """ + + class RouteLegStepLocalizedValues(proto.Message): + r"""Text representations of certain properties. + + Attributes: + distance (google.type.localized_text_pb2.LocalizedText): + Travel distance represented in text form. + static_duration (google.type.localized_text_pb2.LocalizedText): + Duration without taking traffic conditions + into consideration, represented in text form. + """ + + distance: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + static_duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=3, + message=localized_text_pb2.LocalizedText, + ) + + 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', + ) + localized_values: RouteLegStepLocalizedValues = proto.Field( + proto.MESSAGE, + number=8, + message=RouteLegStepLocalizedValues, + ) + transit_details: 'RouteLegStepTransitDetails' = proto.Field( + proto.MESSAGE, + number=9, + message='RouteLegStepTransitDetails', + ) + travel_mode: route_travel_mode.RouteTravelMode = proto.Field( + proto.ENUM, + number=10, + enum=route_travel_mode.RouteTravelMode, + ) + + +class RouteLegStepTransitDetails(proto.Message): + r"""Additional information for the ``RouteLegStep`` related to + ``TRANSIT`` routes. + + Attributes: + stop_details (google.maps.routing_v2.types.RouteLegStepTransitDetails.TransitStopDetails): + Information about the arrival and departure + stops for the step. + localized_values (google.maps.routing_v2.types.RouteLegStepTransitDetails.TransitDetailsLocalizedValues): + Text representations of properties of the + ``RouteLegStepTransitDetails``. + headsign (str): + Specifies the direction in which to travel on + this line as marked on the vehicle or at the + departure stop. The direction is often the + terminus station. + headway (google.protobuf.duration_pb2.Duration): + Specifies the expected time as a duration + between departures from the same stop at this + time. For example, with a headway seconds value + of 600, you would expect a ten minute wait if + you should miss your bus. + transit_line (google.maps.routing_v2.types.TransitLine): + Information about the transit line used in + this step. + stop_count (int): + The number of stops from the departure to the arrival stop. + This count includes the arrival stop, but excludes the + departure stop. For example, if your route leaves from Stop + A, passes through stops B and C, and arrives at stop D, + stop_count returns 3. + trip_short_text (str): + The text that appears in schedules and sign boards to + identify a transit trip to passengers. The text should + uniquely identify a trip within a service day. For example, + "538" is the ``trip_short_text`` of the Amtrak train that + leaves San Jose, CA at 15:10 on weekdays to Sacramento, CA. + """ + + class TransitStopDetails(proto.Message): + r"""Details about the transit stops for the ``RouteLegStep``. + + Attributes: + arrival_stop (google.maps.routing_v2.types.TransitStop): + Information about the arrival stop for the + step. + arrival_time (google.protobuf.timestamp_pb2.Timestamp): + The estimated time of arrival for the step. + departure_stop (google.maps.routing_v2.types.TransitStop): + Information about the departure stop for the + step. + departure_time (google.protobuf.timestamp_pb2.Timestamp): + The estimated time of departure for the step. + """ + + arrival_stop: transit.TransitStop = proto.Field( + proto.MESSAGE, + number=1, + message=transit.TransitStop, + ) + arrival_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + departure_stop: transit.TransitStop = proto.Field( + proto.MESSAGE, + number=3, + message=transit.TransitStop, + ) + departure_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + class TransitDetailsLocalizedValues(proto.Message): + r"""Localized descriptions of values for ``RouteTransitDetails``. + + Attributes: + arrival_time (google.maps.routing_v2.types.LocalizedTime): + Time in its formatted text representation + with a corresponding time zone. + departure_time (google.maps.routing_v2.types.LocalizedTime): + Time in its formatted text representation + with a corresponding time zone. + """ + + arrival_time: localized_time.LocalizedTime = proto.Field( + proto.MESSAGE, + number=1, + message=localized_time.LocalizedTime, + ) + departure_time: localized_time.LocalizedTime = proto.Field( + proto.MESSAGE, + number=2, + message=localized_time.LocalizedTime, + ) + + stop_details: TransitStopDetails = proto.Field( + proto.MESSAGE, + number=1, + message=TransitStopDetails, + ) + localized_values: TransitDetailsLocalizedValues = proto.Field( + proto.MESSAGE, + number=2, + message=TransitDetailsLocalizedValues, + ) + headsign: str = proto.Field( + proto.STRING, + number=3, + ) + headway: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + transit_line: transit.TransitLine = proto.Field( + proto.MESSAGE, + number=5, + message=transit.TransitLine, + ) + stop_count: int = proto.Field( + proto.INT32, + number=6, + ) + trip_short_text: str = proto.Field( + proto.STRING, + number=7, + ) + + +__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..57aa11e9666e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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. + SHORTER_DISTANCE (4): + Shorter travel distance route. This is an + experimental feature. + """ + ROUTE_LABEL_UNSPECIFIED = 0 + DEFAULT_ROUTE = 1 + DEFAULT_ROUTE_ALTERNATE = 2 + FUEL_EFFICIENT = 3 + SHORTER_DISTANCE = 4 + + +__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..a8a386928907 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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): + When set to true, avoids toll roads where reasonable, giving + preference to routes not containing toll roads. Applies only + to the ``DRIVE`` and ``TWO_WHEELER`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + avoid_highways (bool): + When set to true, avoids highways where reasonable, giving + preference to routes not containing highways. Applies only + to the ``DRIVE`` and ``TWO_WHEELER`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + avoid_ferries (bool): + When set to true, avoids ferries where reasonable, giving + preference to routes not containing ferries. Applies only to + the ``DRIVE`` and\ ``TWO_WHEELER`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + avoid_indoor (bool): + When set to true, avoids navigating indoors where + reasonable, giving preference 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..674af4e560a3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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. + TRANSIT (7): + Travel by public transit routes, where + available. + """ + TRAVEL_MODE_UNSPECIFIED = 0 + DRIVE = 1 + BICYCLE = 2 + WALK = 3 + TWO_WHEELER = 4 + TRANSIT = 7 + + +__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..ea00e0f72970 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py @@ -0,0 +1,732 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 traffic_model as gmr_traffic_model +from google.maps.routing_v2.types import transit_preferences as gmr_transit_preferences +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 +from google.type import localized_text_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. NOTE: You can only specify a ``departure_time`` in + the past when + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] + is set to ``TRANSIT``. Transit trips are available for up to + 7 days in the past or 100 days in the future. + arrival_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The arrival time. NOTE: Can only be set when + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] is + set to ``TRANSIT``. You can specify either + ``departure_time`` or ``arrival_time``, but not both. + Transit trips are available for up to 7 days in the past or + 100 days in the future. + 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 `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 + `Country code top-level + domains `__. + units (google.maps.routing_v2.types.Units): + Optional. Specifies the units of measure for the display + fields. These fields include 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 first origin. + optimize_waypoint_order (bool): + Optional. If set to true, the service attempts to minimize + the overall cost of the route by re-ordering the specified + intermediate waypoints. The request fails if any of the + intermediate waypoints is a ``via`` waypoint. Use + ``ComputeRoutesResponse.Routes.optimized_intermediate_waypoint_index`` + to find the new ordering. If + ``ComputeRoutesResponseroutes.optimized_intermediate_waypoint_index`` + is not requested in the ``X-Goog-FieldMask`` header, the + request fails. If ``optimize_waypoint_order`` is set to + false, + ``ComputeRoutesResponse.optimized_intermediate_waypoint_index`` + will be empty. + 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. When using this feature, look for + [``route_labels``][google.maps.routing.v2.Route.route_labels] + on the resulting routes. + 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. + traffic_model (google.maps.routing_v2.types.TrafficModel): + Optional. Specifies the assumptions to use when calculating + time in traffic. This setting affects the value returned in + the duration field in the + [``Route``][google.maps.routing.v2.Route] and + [``RouteLeg``][google.maps.routing.v2.RouteLeg] which + contains the predicted time in traffic based on historical + averages. ``TrafficModel`` is only available for requests + that have set + [``RoutingPreference``][google.maps.routing.v2.RoutingPreference] + to ``TRAFFIC_AWARE_OPTIMAL`` and + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] + to ``DRIVE``. Defaults to ``BEST_GUESS`` if traffic is + requested and ``TrafficModel`` is not specified. + transit_preferences (google.maps.routing_v2.types.TransitPreferences): + Optional. Specifies preferences that influence the route + returned for ``TRANSIT`` routes. NOTE: You can only specify + a ``transit_preferences`` when + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] + is set to ``TRANSIT``. + """ + 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. + SHORTER_DISTANCE (2): + Route with shorter travel distance. This is an experimental + feature. + + For ``DRIVE`` requests, this feature prioritizes shorter + distance over driving comfort. For example, it may prefer + local roads instead of highways, take dirt roads, cut + through parking lots, etc. This feature does not return any + maneuvers that Google Maps knows to be illegal. + + For ``BICYCLE`` and ``TWO_WHEELER`` requests, this feature + returns routes similar to those returned when you don't + specify ``requested_reference_routes``. + + This feature is not compatible with any other travel modes, + via intermediate waypoints, or ``optimize_waypoint_order``; + such requests will fail. However, you can use it with any + ``routing_preference``. + """ + REFERENCE_ROUTE_UNSPECIFIED = 0 + FUEL_EFFICIENT = 1 + SHORTER_DISTANCE = 2 + + 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). + HTML_FORMATTED_NAVIGATION_INSTRUCTIONS (4): + ```NavigationInstructions`` `__ + presented as a formatted HTML text string. This content is + meant to be read as-is. This content is for display only. Do + not programmatically parse it. + """ + EXTRA_COMPUTATION_UNSPECIFIED = 0 + TOLLS = 1 + FUEL_CONSUMPTION = 2 + TRAFFIC_ON_POLYLINE = 3 + HTML_FORMATTED_NAVIGATION_INSTRUCTIONS = 4 + + 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, + ) + arrival_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + 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, + ) + optimize_waypoint_order: bool = proto.Field( + proto.BOOL, + number=13, + ) + 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, + ) + traffic_model: gmr_traffic_model.TrafficModel = proto.Field( + proto.ENUM, + number=18, + enum=gmr_traffic_model.TrafficModel, + ) + transit_preferences: gmr_transit_preferences.TransitPreferences = proto.Field( + proto.MESSAGE, + number=20, + message=gmr_transit_preferences.TransitPreferences, + ) + + +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 sum of the number of origins + the number of + destinations specified as either ``place_id`` or + ``address`` must be no greater than 50. + - The product of number of origins × number of destinations + must be no greater than 625 in any case. + - The product of the number of origins × number of + destinations must be no greater than 100 if + routing_preference is set to ``TRAFFIC_AWARE_OPTIMAL``. + - The product of the number of origins × number of + destinations must be no greater than 100 if travel_mode + is set to ``TRANSIT``. + 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, + then this value defaults to the time that you made the + request. NOTE: You can only specify a ``departure_time`` in + the past when + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] + is set to ``TRANSIT``. + arrival_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The arrival time. NOTE: Can only be set when + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] + is set to ``TRANSIT``. You can specify either + ``departure_time`` or ``arrival_time``, but not both. + language_code (str): + Optional. The BCP-47 language code, such as "en-US" or + "sr-Latn". For more information, see `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 + `Country code top-level + domains `__. + units (google.maps.routing_v2.types.Units): + Optional. Specifies the units of measure for + the display fields. + 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. + traffic_model (google.maps.routing_v2.types.TrafficModel): + Optional. Specifies the assumptions to use when calculating + time in traffic. This setting affects the value returned in + the duration field in the + [RouteMatrixElement][google.maps.routing.v2.RouteMatrixElement] + which contains the predicted time in traffic based on + historical averages. + [RoutingPreference][google.maps.routing.v2.RoutingPreference] + to ``TRAFFIC_AWARE_OPTIMAL`` and + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] to + ``DRIVE``. Defaults to ``BEST_GUESS`` if traffic is + requested and ``TrafficModel`` is not specified. + transit_preferences (google.maps.routing_v2.types.TransitPreferences): + Optional. Specifies preferences that influence the route + returned for ``TRANSIT`` routes. NOTE: You can only specify + a ``transit_preferences`` when + [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] is + set to ``TRANSIT``. + """ + 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, + ) + arrival_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + region_code: str = proto.Field( + proto.STRING, + number=9, + ) + units: gmr_units.Units = proto.Field( + proto.ENUM, + number=7, + enum=gmr_units.Units, + ) + extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=ExtraComputation, + ) + traffic_model: gmr_traffic_model.TrafficModel = proto.Field( + proto.ENUM, + number=10, + enum=gmr_traffic_model.TrafficModel, + ) + transit_preferences: gmr_transit_preferences.TransitPreferences = proto.Field( + proto.MESSAGE, + number=12, + message=gmr_transit_preferences.TransitPreferences, + ) + + +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"""Contains 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. + localized_values (google.maps.routing_v2.types.RouteMatrixElement.LocalizedValues): + Text representations of properties of the + ``RouteMatrixElement``. + """ + + class LocalizedValues(proto.Message): + r"""Text representations of certain properties. + + Attributes: + distance (google.type.localized_text_pb2.LocalizedText): + Travel distance represented in text form. + duration (google.type.localized_text_pb2.LocalizedText): + Duration represented in text form taking traffic conditions + into consideration. Note: If traffic information was not + requested, this value is the same value as static_duration. + static_duration (google.type.localized_text_pb2.LocalizedText): + Duration represented in text form without + taking traffic conditions into consideration. + transit_fare (google.type.localized_text_pb2.LocalizedText): + Transit fare represented in text form. + """ + + distance: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=2, + message=localized_text_pb2.LocalizedText, + ) + static_duration: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=3, + message=localized_text_pb2.LocalizedText, + ) + transit_fare: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=4, + message=localized_text_pb2.LocalizedText, + ) + + 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, + ) + localized_values: LocalizedValues = proto.Field( + proto.MESSAGE, + number=10, + message=LocalizedValues, + ) + + +__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..a0bd24974a2d --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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``, the route and duration chosen + are based on road network and average time-independent + traffic conditions, not current road conditions. + Consequently, routes may include roads that are temporarily + closed. 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..5ace8166d68d --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..c6cf129bc732 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..d0de0e8a78a8 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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. + JP_ETC (98): + Japan + ETC. Electronic wireless system to collect + tolls. https://www.go-etc.jp/ + JP_ETC2 (99): + Japan + ETC2.0. New version of ETC with further discount + and bidirectional communication between devices + on vehicles and antennas on the road. + https://www.go-etc.jp/etc2/index.html + 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. + Deprecated as this pass type no longer exists. + US_MI_IQ_TAG (95): + 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_AVI_TAG (97): + TX, 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_FUEGO_TAG (96): + 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_MOV_PASS (100): + 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 + JP_ETC = 98 + JP_ETC2 = 99 + 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_IQ_TAG = 95 + 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_AVI_TAG = 97 + 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_FUEGO_TAG = 96 + 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_MOV_PASS = 100 + 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/traffic_model.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py new file mode 100644 index 000000000000..0f78d92f1f45 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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={ + 'TrafficModel', + }, +) + + +class TrafficModel(proto.Enum): + r"""Specifies the assumptions to use when calculating time in traffic. + This setting affects the value returned in the ``duration`` field in + the response, which contains the predicted time in traffic based on + historical averages. + + Values: + TRAFFIC_MODEL_UNSPECIFIED (0): + Unused. If specified, will default to ``BEST_GUESS``. + BEST_GUESS (1): + Indicates that the returned ``duration`` should be the best + estimate of travel time given what is known about both + historical traffic conditions and live traffic. Live traffic + becomes more important the closer the ``departure_time`` is + to now. + PESSIMISTIC (2): + Indicates that the returned duration should + be longer than the actual travel time on most + days, though occasional days with particularly + bad traffic conditions may exceed this value. + OPTIMISTIC (3): + Indicates that the returned duration should + be shorter than the actual travel time on most + days, though occasional days with particularly + good traffic conditions may be faster than this + value. + """ + TRAFFIC_MODEL_UNSPECIFIED = 0 + BEST_GUESS = 1 + PESSIMISTIC = 2 + OPTIMISTIC = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py new file mode 100644 index 000000000000..bfa6ba1e738e --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py @@ -0,0 +1,259 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from google.type import localized_text_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.maps.routing.v2', + manifest={ + 'TransitAgency', + 'TransitLine', + 'TransitStop', + 'TransitVehicle', + }, +) + + +class TransitAgency(proto.Message): + r"""A transit agency that operates a transit line. + + Attributes: + name (str): + The name of this transit agency. + phone_number (str): + The transit agency's locale-specific + formatted phone number. + uri (str): + The transit agency's URI. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + phone_number: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + ) + + +class TransitLine(proto.Message): + r"""Contains information about the transit line used in this + step. + + Attributes: + agencies (MutableSequence[google.maps.routing_v2.types.TransitAgency]): + The transit agency (or agencies) that + operates this transit line. + name (str): + The full name of this transit line, For + example, "8 Avenue Local". + uri (str): + the URI for this transit line as provided by + the transit agency. + color (str): + The color commonly used in signage for this + line. Represented in hexadecimal. + icon_uri (str): + The URI for the icon associated with this + line. + name_short (str): + The short name of this transit line. This + name will normally be a line number, such as + "M7" or "355". + text_color (str): + The color commonly used in text on signage + for this line. Represented in hexadecimal. + vehicle (google.maps.routing_v2.types.TransitVehicle): + The type of vehicle that operates on this + transit line. + """ + + agencies: MutableSequence['TransitAgency'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TransitAgency', + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + ) + color: str = proto.Field( + proto.STRING, + number=4, + ) + icon_uri: str = proto.Field( + proto.STRING, + number=5, + ) + name_short: str = proto.Field( + proto.STRING, + number=6, + ) + text_color: str = proto.Field( + proto.STRING, + number=7, + ) + vehicle: 'TransitVehicle' = proto.Field( + proto.MESSAGE, + number=8, + message='TransitVehicle', + ) + + +class TransitStop(proto.Message): + r"""Information about a transit stop. + + Attributes: + name (str): + The name of the transit stop. + location (google.maps.routing_v2.types.Location): + The location of the stop expressed in + latitude/longitude coordinates. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + location: gmr_location.Location = proto.Field( + proto.MESSAGE, + number=2, + message=gmr_location.Location, + ) + + +class TransitVehicle(proto.Message): + r"""Information about a vehicle used in transit routes. + + Attributes: + name (google.type.localized_text_pb2.LocalizedText): + The name of this vehicle, capitalized. + type_ (google.maps.routing_v2.types.TransitVehicle.TransitVehicleType): + The type of vehicle used. + icon_uri (str): + The URI for an icon associated with this + vehicle type. + local_icon_uri (str): + The URI for the icon associated with this + vehicle type, based on the local transport + signage. + """ + class TransitVehicleType(proto.Enum): + r"""The type of vehicles for transit routes. + + Values: + TRANSIT_VEHICLE_TYPE_UNSPECIFIED (0): + Unused. + BUS (1): + Bus. + CABLE_CAR (2): + A vehicle that operates on a cable, usually on the ground. + Aerial cable cars may be of the type ``GONDOLA_LIFT``. + COMMUTER_TRAIN (3): + Commuter rail. + FERRY (4): + Ferry. + FUNICULAR (5): + A vehicle that is pulled up a steep incline + by a cable. A Funicular typically consists of + two cars, with each car acting as a + counterweight for the other. + GONDOLA_LIFT (6): + An aerial cable car. + HEAVY_RAIL (7): + Heavy rail. + HIGH_SPEED_TRAIN (8): + High speed train. + INTERCITY_BUS (9): + Intercity bus. + LONG_DISTANCE_TRAIN (10): + Long distance train. + METRO_RAIL (11): + Light rail transit. + MONORAIL (12): + Monorail. + OTHER (13): + All other vehicles. + RAIL (14): + Rail. + SHARE_TAXI (15): + Share taxi is a kind of bus with the ability + to drop off and pick up passengers anywhere on + its route. + SUBWAY (16): + Underground light rail. + TRAM (17): + Above ground light rail. + TROLLEYBUS (18): + Trolleybus. + """ + TRANSIT_VEHICLE_TYPE_UNSPECIFIED = 0 + BUS = 1 + CABLE_CAR = 2 + COMMUTER_TRAIN = 3 + FERRY = 4 + FUNICULAR = 5 + GONDOLA_LIFT = 6 + HEAVY_RAIL = 7 + HIGH_SPEED_TRAIN = 8 + INTERCITY_BUS = 9 + LONG_DISTANCE_TRAIN = 10 + METRO_RAIL = 11 + MONORAIL = 12 + OTHER = 13 + RAIL = 14 + SHARE_TAXI = 15 + SUBWAY = 16 + TRAM = 17 + TROLLEYBUS = 18 + + name: localized_text_pb2.LocalizedText = proto.Field( + proto.MESSAGE, + number=1, + message=localized_text_pb2.LocalizedText, + ) + type_: TransitVehicleType = proto.Field( + proto.ENUM, + number=2, + enum=TransitVehicleType, + ) + icon_uri: str = proto.Field( + proto.STRING, + number=3, + ) + local_icon_uri: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py new file mode 100644 index 000000000000..7786f8811da3 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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={ + 'TransitPreferences', + }, +) + + +class TransitPreferences(proto.Message): + r"""Preferences for ``TRANSIT`` based routes that influence the route + that is returned. + + Attributes: + allowed_travel_modes (MutableSequence[google.maps.routing_v2.types.TransitPreferences.TransitTravelMode]): + A set of travel modes to use when getting a ``TRANSIT`` + route. Defaults to all supported modes of travel. + routing_preference (google.maps.routing_v2.types.TransitPreferences.TransitRoutingPreference): + A routing preference that, when specified, influences the + ``TRANSIT`` route returned. + """ + class TransitTravelMode(proto.Enum): + r"""A set of values used to specify the mode of transit. + + Values: + TRANSIT_TRAVEL_MODE_UNSPECIFIED (0): + No transit travel mode specified. + BUS (1): + Travel by bus. + SUBWAY (2): + Travel by subway. + TRAIN (3): + Travel by train. + LIGHT_RAIL (4): + Travel by light rail or tram. + RAIL (5): + Travel by rail. This is equivalent to a combination of + ``SUBWAY``, ``TRAIN``, and ``LIGHT_RAIL``. + """ + TRANSIT_TRAVEL_MODE_UNSPECIFIED = 0 + BUS = 1 + SUBWAY = 2 + TRAIN = 3 + LIGHT_RAIL = 4 + RAIL = 5 + + class TransitRoutingPreference(proto.Enum): + r"""Specifies routing preferences for transit routes. + + Values: + TRANSIT_ROUTING_PREFERENCE_UNSPECIFIED (0): + No preference specified. + LESS_WALKING (1): + Indicates that the calculated route should + prefer limited amounts of walking. + FEWER_TRANSFERS (2): + Indicates that the calculated route should + prefer a limited number of transfers. + """ + TRANSIT_ROUTING_PREFERENCE_UNSPECIFIED = 0 + LESS_WALKING = 1 + FEWER_TRANSFERS = 2 + + allowed_travel_modes: MutableSequence[TransitTravelMode] = proto.RepeatedField( + proto.ENUM, + number=1, + enum=TransitTravelMode, + ) + routing_preference: TransitRoutingPreference = proto.Field( + proto.ENUM, + number=2, + enum=TransitRoutingPreference, + ) + + +__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..911de7f76fd7 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..9da25c5d86d9 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..59b79853333c --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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"""Contains the vehicle information, such as the vehicle + emission type. + + Attributes: + emission_type (google.maps.routing_v2.types.VehicleEmissionType): + Describes the vehicle's emission type. Applies only to the + ``DRIVE`` + [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. + """ + + 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..d6748f9d6db3 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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..b99c4c5bb684 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-maps-routing' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + 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)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + 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)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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', + '-p', + '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==7.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, + ) 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..f326b5e2134c --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..9d1e1ae87791 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..ba59057436a1 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..49d835374e19 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..8c26fc095087 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', 'arrival_time', 'language_code', 'region_code', 'units', 'extra_computations', 'traffic_model', 'transit_preferences', ), + 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'arrival_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'region_code', 'units', 'optimize_waypoint_order', 'requested_reference_routes', 'extra_computations', 'traffic_model', 'transit_preferences', ), + } + + 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..4336dee44a87 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re + +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 = None + +with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +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.1, <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.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=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", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-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.find_namespace_packages() + if package.startswith("google") +] + +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", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + 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.13.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.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..277853c664a0 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# 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.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +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..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..7b3de3117f38 --- /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 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..2dd1e032be26 --- /dev/null +++ b/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py @@ -0,0 +1,2328 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +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 + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +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.api_core import retry as retries +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 traffic_model +from google.maps.routing_v2.types import transit_preferences +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 + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# 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 + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 + +def test__read_environment_variables(): + assert RoutesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RoutesClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RoutesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + RoutesClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert RoutesClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RoutesClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RoutesClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RoutesClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert RoutesClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert RoutesClient._get_client_cert_source(None, False) is None + assert RoutesClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert RoutesClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + 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_default_cert_source): + assert RoutesClient._get_client_cert_source(None, True) is mock_default_cert_source + assert RoutesClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RoutesClient._DEFAULT_UNIVERSE + default_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert RoutesClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert RoutesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RoutesClient.DEFAULT_MTLS_ENDPOINT + assert RoutesClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert RoutesClient._get_api_endpoint(None, None, default_universe, "always") == RoutesClient.DEFAULT_MTLS_ENDPOINT + assert RoutesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RoutesClient.DEFAULT_MTLS_ENDPOINT + assert RoutesClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert RoutesClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + RoutesClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert RoutesClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert RoutesClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert RoutesClient._get_universe_domain(None, None) == RoutesClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + RoutesClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@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_TEMPLATE", modify_default_endpoint_template(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + 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_TEMPLATE", modify_default_endpoint_template(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + 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 + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + RoutesClient, RoutesAsyncClient +]) +@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) +@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) +def test_routes_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RoutesClient._DEFAULT_UNIVERSE + default_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + 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] + request = routes_service.ComputeRoutesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, routes_service.ComputeRoutesResponse) + + +def test_compute_routes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = routes_service.ComputeRoutesRequest( + language_code='language_code_value', + region_code='region_code_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.compute_routes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRoutesRequest( + language_code='language_code_value', + region_code='region_code_value', + ) + +def test_compute_routes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.compute_routes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.compute_routes] = mock_rpc + request = {} + client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_routes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_compute_routes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RoutesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.compute_routes in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.compute_routes] = mock_rpc + + request = {} + await client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.compute_routes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): + client = RoutesAsyncClient( + credentials=async_anonymous_credentials(), + 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] + request = routes_service.ComputeRoutesRequest() + assert args[0] == request + + # 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] + request = routes_service.ComputeRouteMatrixRequest() + assert args[0] == request + + # 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_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = routes_service.ComputeRouteMatrixRequest( + language_code='language_code_value', + region_code='region_code_value', + ) + + # 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: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.compute_route_matrix(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == routes_service.ComputeRouteMatrixRequest( + language_code='language_code_value', + region_code='region_code_value', + ) + +def test_compute_route_matrix_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.compute_route_matrix in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.compute_route_matrix] = mock_rpc + request = {} + client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_route_matrix(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_compute_route_matrix_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RoutesAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.compute_route_matrix in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.compute_route_matrix] = mock_rpc + + request = {} + await client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.compute_route_matrix(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): + client = RoutesAsyncClient( + credentials=async_anonymous_credentials(), + 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] + request = routes_service.ComputeRouteMatrixRequest() + assert args[0] == request + + # 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) + + +def test_compute_routes_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.compute_routes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.compute_routes] = mock_rpc + + request = {} + client.compute_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_routes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +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, + 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 + + # Convert return value to protobuf type + return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(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", ))) + + +def test_compute_route_matrix_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.compute_route_matrix in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.compute_route_matrix] = mock_rpc + + request = {} + client.compute_route_matrix(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_route_matrix(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +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, + 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 + + # Convert return value to protobuf type + return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(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", ))) + + +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 = client_options.ClientOptions() + 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() + +def test_transport_kind_grpc(): + transport = RoutesClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_compute_routes_empty_call_grpc(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + call.return_value = routes_service.ComputeRoutesResponse() + client.compute_routes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRoutesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_compute_route_matrix_empty_call_grpc(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + call.return_value = iter([routes_service.RouteMatrixElement()]) + client.compute_route_matrix(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRouteMatrixRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = RoutesAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RoutesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_compute_routes_empty_call_grpc_asyncio(): + client = RoutesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, 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( + )) + await client.compute_routes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRoutesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_compute_route_matrix_empty_call_grpc_asyncio(): + client = RoutesAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, 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()]) + await client.compute_route_matrix(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRouteMatrixRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = RoutesClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_compute_routes_rest_bad_request(request_type=routes_service.ComputeRoutesRequest): + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.compute_routes(request) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRoutesRequest, + dict, +]) +def test_compute_routes_rest_call_success(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 = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = routes_service.ComputeRoutesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(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) + + +@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 = mock.Mock() + req.return_value.status_code = 200 + return_value = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) + req.return_value.content = return_value + + 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_route_matrix_rest_bad_request(request_type=routes_service.ComputeRouteMatrixRequest): + 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 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 = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.compute_route_matrix(request) + + +@pytest.mark.parametrize("request_type", [ + routes_service.ComputeRouteMatrixRequest, + dict, +]) +def test_compute_route_matrix_rest_call_success(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 = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = routes_service.RouteMatrixElement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) + req.return_value = response_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 + + +@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 = mock.Mock() + req.return_value.status_code = 200 + return_value = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) + req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) + + 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_initialize_client_w_rest(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_compute_routes_empty_call_rest(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_routes), + '__call__') as call: + client.compute_routes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRoutesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_compute_route_matrix_empty_call_rest(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_route_matrix), + '__call__') as call: + client.compute_route_matrix(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = routes_service.ComputeRouteMatrixRequest() + + assert args[0] == request_msg + + +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) + + +def test_transport_close_grpc(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = RoutesAsyncClient( + credentials=async_anonymous_credentials(), + 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_rest(): + client = RoutesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + 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 4a7d873ba4bcff2c06818d1dc850b90011723fca Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 26 Nov 2024 21:00:43 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-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 - .../v2/docs/_static/custom.css | 3 - .../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 | 113 - .../v2/google/maps/routing/gapic_version.py | 16 - .../v2/google/maps/routing/py.typed | 2 - .../v2/google/maps/routing_v2/__init__.py | 114 - .../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 | 460 ---- .../maps/routing_v2/services/routes/client.py | 781 ------ .../services/routes/transports/README.rst | 9 - .../services/routes/transports/__init__.py | 38 - .../services/routes/transports/base.py | 167 -- .../services/routes/transports/grpc.py | 369 --- .../routes/transports/grpc_asyncio.py | 395 --- .../services/routes/transports/rest.py | 384 --- .../services/routes/transports/rest_base.py | 185 -- .../google/maps/routing_v2/types/__init__.py | 150 -- .../maps/routing_v2/types/fallback_info.py | 105 - .../routing_v2/types/geocoding_results.py | 127 - .../maps/routing_v2/types/localized_time.py | 58 - .../google/maps/routing_v2/types/location.py | 63 - .../google/maps/routing_v2/types/maneuver.py | 103 - .../types/navigation_instruction.py | 58 - .../google/maps/routing_v2/types/polyline.py | 113 - .../v2/google/maps/routing_v2/types/route.py | 790 ------ .../maps/routing_v2/types/route_label.py | 62 - .../maps/routing_v2/types/route_modifiers.py | 98 - .../routing_v2/types/route_travel_mode.py | 63 - .../maps/routing_v2/types/routes_service.py | 732 ------ .../routing_v2/types/routing_preference.py | 71 - .../types/speed_reading_interval.py | 92 - .../google/maps/routing_v2/types/toll_info.py | 57 - .../maps/routing_v2/types/toll_passes.py | 376 --- .../maps/routing_v2/types/traffic_model.py | 64 - .../google/maps/routing_v2/types/transit.py | 259 -- .../routing_v2/types/transit_preferences.py | 97 - .../v2/google/maps/routing_v2/types/units.py | 49 - .../routing_v2/types/vehicle_emission_type.py | 56 - .../maps/routing_v2/types/vehicle_info.py | 51 - .../google/maps/routing_v2/types/waypoint.py | 126 - .../google-maps-routing/v2/mypy.ini | 3 - .../google-maps-routing/v2/noxfile.py | 280 -- ...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 | 99 - .../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.13.txt | 7 - .../v2/testing/constraints-3.7.txt | 11 - .../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 | 2328 ----------------- .../google/maps/routing/gapic_version.py | 2 +- .../google/maps/routing_v2/gapic_version.py | 2 +- .../google/maps/routing_v2/types/route.py | 35 +- .../maps/routing_v2/types/route_label.py | 4 + .../maps/routing_v2/types/routes_service.py | 27 +- ...ippet_metadata_google.maps.routing.v2.json | 2 +- 79 files changed, 49 insertions(+), 11021 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/_static/custom.css 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/README.rst 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/services/routes/transports/rest_base.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/localized_time.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/traffic_model.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py delete mode 100644 owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.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.13.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/_static/custom.css b/owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} 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 4b30f5a14b3e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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"2023, 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 = 'en' - -# 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 3a2d987095fc..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 6435ad0166ed..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing/__init__.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.localized_time import LocalizedTime -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 RouteLegStepTransitDetails -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.traffic_model import TrafficModel -from google.maps.routing_v2.types.transit import TransitAgency -from google.maps.routing_v2.types.transit import TransitLine -from google.maps.routing_v2.types.transit import TransitStop -from google.maps.routing_v2.types.transit import TransitVehicle -from google.maps.routing_v2.types.transit_preferences import TransitPreferences -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', - 'LocalizedTime', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTransitDetails', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'TrafficModel', - 'TransitAgency', - 'TransitLine', - 'TransitStop', - 'TransitVehicle', - 'TransitPreferences', - '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 558c8aab67c5..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.0.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 cdae66b5d7f6..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/__init__.py +++ /dev/null @@ -1,114 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.localized_time import LocalizedTime -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 RouteLegStepTransitDetails -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.traffic_model import TrafficModel -from .types.transit import TransitAgency -from .types.transit import TransitLine -from .types.transit import TransitStop -from .types.transit import TransitVehicle -from .types.transit_preferences import TransitPreferences -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', -'LocalizedTime', -'Location', -'Maneuver', -'NavigationInstruction', -'Polyline', -'PolylineEncoding', -'PolylineQuality', -'Route', -'RouteLabel', -'RouteLeg', -'RouteLegStep', -'RouteLegStepTransitDetails', -'RouteLegStepTravelAdvisory', -'RouteLegTravelAdvisory', -'RouteMatrixDestination', -'RouteMatrixElement', -'RouteMatrixElementCondition', -'RouteMatrixOrigin', -'RouteModifiers', -'RouteTravelAdvisory', -'RouteTravelMode', -'RoutesClient', -'RoutingPreference', -'SpeedReadingInterval', -'TollInfo', -'TollPass', -'TrafficModel', -'TransitAgency', -'TransitLine', -'TransitPreferences', -'TransitStop', -'TransitVehicle', -'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 558c8aab67c5..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.0.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 8f6cf068242c..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 1d5f9c21bfea..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 3315c0768267..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/async_client.py +++ /dev/null @@ -1,460 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 re -from typing import Dict, Callable, 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_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # 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 - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = RoutesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RoutesClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = RoutesClient._DEFAULT_UNIVERSE - - 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 - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = RoutesClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RoutesTransport, Callable[..., RoutesTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the routes async 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 (Optional[Union[str,RoutesTransport,Callable[..., RoutesTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the RoutesTransport constructor. - 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. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - 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_async.AsyncRetry): 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. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._transport.compute_routes] - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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_async.AsyncRetry): 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]: - Contains 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. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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._client._transport._wrapped_methods[self._client._transport.compute_route_matrix] - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "RoutesAsyncClient": - 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 fcf4c589de2c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/client.py +++ /dev/null @@ -1,781 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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, Callable, Mapping, MutableMapping, MutableSequence, Optional, Iterable, Sequence, Tuple, Type, Union, cast -import warnings - -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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # 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") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "routes.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "routes.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @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): - """Deprecated. 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. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - 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 - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - 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`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = RoutesClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = RoutesClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = RoutesClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RoutesTransport, Callable[..., 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 (Optional[Union[str,RoutesTransport,Callable[..., RoutesTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the RoutesTransport constructor. - 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. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = RoutesClient._read_environment_variables() - self._client_cert_source = RoutesClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = RoutesClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._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. - transport_provided = isinstance(transport, RoutesTransport) - if transport_provided: - # transport is a RoutesTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(RoutesTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - RoutesClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - 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_init: Union[Type[RoutesTransport], Callable[..., RoutesTransport]] = ( - RoutesClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., RoutesTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._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. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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] - - # Validate the universe domain. - self._validate_universe_domain() - - # 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]: - Contains 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. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - 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] - - # Validate the universe domain. - self._validate_universe_domain() - - # 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/README.rst b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst deleted file mode 100644 index ece3f327f1db..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`RoutesTransport` is the ABC for all transports. -- public child `RoutesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `RoutesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseRoutesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `RoutesRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). 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 cac74dd752a0..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 ecdfa6e5fcc0..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/base.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 (default: 'routes.googleapis.com'). - 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 not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # 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 and not self._ignore_credentials: - 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 - - @property - def host(self): - return self._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 223360b6ba76..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc.py +++ /dev/null @@ -1,369 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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[Union[grpc.Channel, Callable[..., 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 (default: 'routes.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - 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 a ``channel`` instance 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 a ``channel`` instance 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 isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # 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: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - 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 e4752aeff4c2..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/grpc_asyncio.py +++ /dev/null @@ -1,395 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 inspect -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.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -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`. - 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[Union[aio.Channel, Callable[..., 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 (default: 'routes.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - 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 a ``channel`` instance 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 a ``channel`` instance 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 isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # 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: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - 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._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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 _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.compute_routes: self._wrap_method( - self.compute_routes, - default_timeout=None, - client_info=client_info, - ), - self.compute_route_matrix: self._wrap_method( - self.compute_route_matrix, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__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 e62eb44c3f16..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest.py +++ /dev/null @@ -1,384 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -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 gapic_v1 - -from google.protobuf import json_format - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.maps.routing_v2.types import routes_service - - -from .rest_base import _BaseRoutesRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{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(_BaseRoutesRestTransport): - """REST backend synchronous 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 (default: 'routes.googleapis.com'). - 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 - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - 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(_BaseRoutesRestTransport._BaseComputeRouteMatrix, RoutesRestStub): - def __hash__(self): - return hash("RoutesRestTransport.ComputeRouteMatrix") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - stream=True, - ) - return response - - 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: - Contains route information computed - for an origin/destination pair in the - ComputeRouteMatrix API. This proto can - be streamed to the client. - - """ - - http_options = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_http_options() - request, metadata = self._interceptor.pre_compute_route_matrix(request, metadata) - transcoded_request = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_transcoded_request(http_options, request) - - body = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseRoutesRestTransport._BaseComputeRouteMatrix._get_query_params_json(transcoded_request) - - # Send the request - response = RoutesRestTransport._ComputeRouteMatrix._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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(_BaseRoutesRestTransport._BaseComputeRoutes, RoutesRestStub): - def __hash__(self): - return hash("RoutesRestTransport.ComputeRoutes") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - 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 = _BaseRoutesRestTransport._BaseComputeRoutes._get_http_options() - request, metadata = self._interceptor.pre_compute_routes(request, metadata) - transcoded_request = _BaseRoutesRestTransport._BaseComputeRoutes._get_transcoded_request(http_options, request) - - body = _BaseRoutesRestTransport._BaseComputeRoutes._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseRoutesRestTransport._BaseComputeRoutes._get_query_params_json(transcoded_request) - - # Send the request - response = RoutesRestTransport._ComputeRoutes._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, 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/services/routes/transports/rest_base.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py deleted file mode 100644 index 89bf86170eeb..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/services/routes/transports/rest_base.py +++ /dev/null @@ -1,185 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import RoutesTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.maps.routing_v2.types import routes_service - - -class _BaseRoutesRestTransport(RoutesTransport): - """Base REST backend transport for Routes. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - 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[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'routes.googleapis.com'). - credentials (Optional[Any]): 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. - 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 - 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 - ) - - class _BaseComputeRouteMatrix: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/distanceMatrix/v2:computeRouteMatrix', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = routes_service.ComputeRouteMatrixRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseRoutesRestTransport._BaseComputeRouteMatrix._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseComputeRoutes: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __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} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/directions/v2:computeRoutes', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = routes_service.ComputeRoutesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseRoutesRestTransport._BaseComputeRoutes._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseRoutesRestTransport', -) 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 56fa2a5f9cbb..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/__init__.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 .localized_time import ( - LocalizedTime, -) -from .location import ( - Location, -) -from .maneuver import ( - Maneuver, -) -from .navigation_instruction import ( - NavigationInstruction, -) -from .polyline import ( - Polyline, - PolylineEncoding, - PolylineQuality, -) -from .route import ( - Route, - RouteLeg, - RouteLegStep, - RouteLegStepTransitDetails, - RouteLegStepTravelAdvisory, - RouteLegTravelAdvisory, - RouteTravelAdvisory, -) -from .route_label import ( - RouteLabel, -) -from .route_modifiers import ( - RouteModifiers, -) -from .route_travel_mode import ( - RouteTravelMode, -) -from .routes_service import ( - ComputeRouteMatrixRequest, - ComputeRoutesRequest, - ComputeRoutesResponse, - RouteMatrixDestination, - RouteMatrixElement, - RouteMatrixOrigin, - RouteMatrixElementCondition, -) -from .routing_preference import ( - RoutingPreference, -) -from .speed_reading_interval import ( - SpeedReadingInterval, -) -from .toll_info import ( - TollInfo, -) -from .toll_passes import ( - TollPass, -) -from .traffic_model import ( - TrafficModel, -) -from .transit import ( - TransitAgency, - TransitLine, - TransitStop, - TransitVehicle, -) -from .transit_preferences import ( - TransitPreferences, -) -from .units import ( - Units, -) -from .vehicle_emission_type import ( - VehicleEmissionType, -) -from .vehicle_info import ( - VehicleInfo, -) -from .waypoint import ( - Waypoint, -) - -__all__ = ( - 'FallbackInfo', - 'FallbackReason', - 'FallbackRoutingMode', - 'GeocodedWaypoint', - 'GeocodingResults', - 'LocalizedTime', - 'Location', - 'Maneuver', - 'NavigationInstruction', - 'Polyline', - 'PolylineEncoding', - 'PolylineQuality', - 'Route', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTransitDetails', - 'RouteLegStepTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteTravelAdvisory', - 'RouteLabel', - 'RouteModifiers', - 'RouteTravelMode', - 'ComputeRouteMatrixRequest', - 'ComputeRoutesRequest', - 'ComputeRoutesResponse', - 'RouteMatrixDestination', - 'RouteMatrixElement', - 'RouteMatrixOrigin', - 'RouteMatrixElementCondition', - 'RoutingPreference', - 'SpeedReadingInterval', - 'TollInfo', - 'TollPass', - 'TrafficModel', - 'TransitAgency', - 'TransitLine', - 'TransitStop', - 'TransitVehicle', - 'TransitPreferences', - '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 e9c371f86902..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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`` - [``RoutingPreference``][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 e7b5ac69343c..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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: `Address types and address component - 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/localized_time.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py deleted file mode 100644 index cd33d5012b85..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/localized_time.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 localized_text_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'LocalizedTime', - }, -) - - -class LocalizedTime(proto.Message): - r"""Localized description of time. - - Attributes: - time (google.type.localized_text_pb2.LocalizedText): - The time specified as a string in a given - time zone. - time_zone (str): - Contains the time zone. The value is the name of the time - zone as defined in the `IANA Time Zone - Database `__, e.g. - "America/New_York". - """ - - time: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - time_zone: 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/location.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/location.py deleted file mode 100644 index 895301cea20d..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 specifies the side of the road - 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, and so on. 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 e8275813708a..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/maneuver.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 (for example, turn left, merge, or - straight). - - 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. - DEPART (19): - Initial maneuver. - NAME_CHANGE (20): - Used to indicate a street name change. - """ - 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 - DEPART = 19 - NAME_CHANGE = 20 - - -__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 f9a930014166..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 (for example, turn left, merge, - or straight). 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 fe776cd21e8b..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 a79f0977ae74..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route.py +++ /dev/null @@ -1,790 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.types import viewport as ggt_viewport -from google.maps.routing_v2.types import localized_time -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 route_travel_mode -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.maps.routing_v2.types import transit -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore -from google.type import money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'Route', - 'RouteTravelAdvisory', - 'RouteLegTravelAdvisory', - 'RouteLegStepTravelAdvisory', - 'RouteLeg', - 'RouteLegStep', - 'RouteLegStepTransitDetails', - }, -) - - -class Route(proto.Message): - r"""Contains 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 travel through the route - without taking traffic conditions into - consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall route polyline. This polyline is 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.types.Viewport): - The viewport bounding box of the polyline. - travel_advisory (google.maps.routing_v2.types.RouteTravelAdvisory): - Additional information about the route. - optimized_intermediate_waypoint_index (MutableSequence[int]): - If you set - [``optimize_waypoint_order``][google.maps.routing.v2.ComputeRoutesRequest.optimize_waypoint_order] - to true, this field contains the optimized ordering of - intermediate waypoints. Otherwise, this field is empty. For - example, if you give an input of Origin: LA; Intermediate - waypoints: Dallas, Bangor, Phoenix; Destination: New York; - and the optimized intermediate waypoint order is Phoenix, - Dallas, Bangor, then this field contains the values [2, 0, - 1]. The index starts with 0 for the first intermediate - waypoint provided in the input. - localized_values (google.maps.routing_v2.types.Route.RouteLocalizedValues): - Text representations of properties of the ``Route``. - route_token (str): - An opaque token that can be passed to `Navigation - SDK `__ - to reconstruct the route during navigation, and, in the - event of rerouting, honor the original intention when the - route was created. Treat this token as an opaque blob. Don't - compare its value across requests as its value may change - even if the service returns the exact same route. - - 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 not supported for requests that - have Via waypoints. - """ - - class RouteLocalizedValues(proto.Message): - r"""Text representations of certain properties. - - Attributes: - distance (google.type.localized_text_pb2.LocalizedText): - Travel distance represented in text form. - duration (google.type.localized_text_pb2.LocalizedText): - Duration, represented in text form and localized to the - region of the query. Takes traffic conditions into - consideration. Note: If you did not request traffic - information, this value is the same value as - ``static_duration``. - static_duration (google.type.localized_text_pb2.LocalizedText): - Duration without taking traffic conditions - into consideration, represented in text form. - transit_fare (google.type.localized_text_pb2.LocalizedText): - Transit fare represented in text form. - """ - - distance: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=2, - message=localized_text_pb2.LocalizedText, - ) - static_duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=3, - message=localized_text_pb2.LocalizedText, - ) - transit_fare: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=4, - message=localized_text_pb2.LocalizedText, - ) - - 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: ggt_viewport.Viewport = proto.Field( - proto.MESSAGE, - number=8, - message=ggt_viewport.Viewport, - ) - travel_advisory: 'RouteTravelAdvisory' = proto.Field( - proto.MESSAGE, - number=9, - message='RouteTravelAdvisory', - ) - optimized_intermediate_waypoint_index: MutableSequence[int] = proto.RepeatedField( - proto.INT32, - number=10, - ) - localized_values: RouteLocalizedValues = proto.Field( - proto.MESSAGE, - number=11, - message=RouteLocalizedValues, - ) - route_token: str = proto.Field( - proto.STRING, - number=12, - ) - - -class RouteTravelAdvisory(proto.Message): - r"""Contains the additional information that the user should be - informed about, such as possible traffic zone restrictions. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Contains information about tolls on the route. This field is - only populated if tolls are expected on the route. If this - field is set, but the ``estimatedPrice`` subfield is not - populated, then the route contains tolls, but the estimated - price is unknown. If this field is not set, then there are - no tolls expected 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 predicted fuel consumption in - microliters. - route_restrictions_partially_ignored (bool): - Returned route may have restrictions that are - not suitable for requested travel mode or route - modifiers. - transit_fare (google.type.money_pb2.Money): - If present, contains the total fare or ticket costs on this - route This property is only returned for ``TRANSIT`` - requests and only for routes where fare information is - available for all transit steps. - """ - - 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, - ) - route_restrictions_partially_ignored: bool = proto.Field( - proto.BOOL, - number=6, - ) - transit_fare: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=7, - message=money_pb2.Money, - ) - - -class RouteLegTravelAdvisory(proto.Message): - r"""Contains the additional information that the user should be - informed about on a leg step, such as possible traffic zone - restrictions. - - Attributes: - toll_info (google.maps.routing_v2.types.TollInfo): - Contains 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 ``RouteLeg`` 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"""Contains the additional information that the user should be - informed about, such as possible traffic zone restrictions 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"""Contains 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 travel through the leg, - calculated without taking traffic conditions - into consideration. - polyline (google.maps.routing_v2.types.Polyline): - The overall polyline for this leg that includes each - ``step``'s polyline. - start_location (google.maps.routing_v2.types.Location): - The start location of this leg. This location 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 location 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): - Contains the additional information that the - user should be informed about, such as possible - traffic zone restrictions, on a route leg. - localized_values (google.maps.routing_v2.types.RouteLeg.RouteLegLocalizedValues): - Text representations of properties of the ``RouteLeg``. - steps_overview (google.maps.routing_v2.types.RouteLeg.StepsOverview): - Overview information about the steps in this ``RouteLeg``. - This field is only populated for TRANSIT routes. - """ - - class RouteLegLocalizedValues(proto.Message): - r"""Text representations of certain properties. - - Attributes: - distance (google.type.localized_text_pb2.LocalizedText): - Travel distance represented in text form. - duration (google.type.localized_text_pb2.LocalizedText): - Duration, represented in text form and localized to the - region of the query. Takes traffic conditions into - consideration. Note: If you did not request traffic - information, this value is the same value as - static_duration. - static_duration (google.type.localized_text_pb2.LocalizedText): - Duration without taking traffic conditions - into consideration, represented in text form. - """ - - distance: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=2, - message=localized_text_pb2.LocalizedText, - ) - static_duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=3, - message=localized_text_pb2.LocalizedText, - ) - - class StepsOverview(proto.Message): - r"""Provides overview information about a list of ``RouteLegStep``\ s. - - Attributes: - multi_modal_segments (MutableSequence[google.maps.routing_v2.types.RouteLeg.StepsOverview.MultiModalSegment]): - Summarized information about different multi-modal segments - of the ``RouteLeg.steps``. This field is not populated if - the ``RouteLeg`` does not contain any multi-modal segments - in the steps. - """ - - class MultiModalSegment(proto.Message): - r"""Provides summarized information about different multi-modal segments - of the ``RouteLeg.steps``. A multi-modal segment is defined as one - or more contiguous ``RouteLegStep`` that have the same - ``RouteTravelMode``. This field is not populated if the ``RouteLeg`` - does not contain any multi-modal segments in the steps. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - step_start_index (int): - The corresponding ``RouteLegStep`` index that is the start - of a multi-modal segment. - - This field is a member of `oneof`_ ``_step_start_index``. - step_end_index (int): - The corresponding ``RouteLegStep`` index that is the end of - a multi-modal segment. - - This field is a member of `oneof`_ ``_step_end_index``. - navigation_instruction (google.maps.routing_v2.types.NavigationInstruction): - NavigationInstruction for the multi-modal - segment. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - The travel mode of the multi-modal segment. - """ - - step_start_index: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - step_end_index: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - navigation_instruction: gmr_navigation_instruction.NavigationInstruction = proto.Field( - proto.MESSAGE, - number=3, - message=gmr_navigation_instruction.NavigationInstruction, - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=4, - enum=route_travel_mode.RouteTravelMode, - ) - - multi_modal_segments: MutableSequence['RouteLeg.StepsOverview.MultiModalSegment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RouteLeg.StepsOverview.MultiModalSegment', - ) - - 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', - ) - localized_values: RouteLegLocalizedValues = proto.Field( - proto.MESSAGE, - number=9, - message=RouteLegLocalizedValues, - ) - steps_overview: StepsOverview = proto.Field( - proto.MESSAGE, - number=10, - message=StepsOverview, - ) - - -class RouteLegStep(proto.Message): - r"""Contains 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): - Contains the additional information that the - user should be informed about, such as possible - traffic zone restrictions, on a leg step. - localized_values (google.maps.routing_v2.types.RouteLegStep.RouteLegStepLocalizedValues): - Text representations of properties of the ``RouteLegStep``. - transit_details (google.maps.routing_v2.types.RouteLegStepTransitDetails): - Details pertaining to this step if the travel mode is - ``TRANSIT``. - travel_mode (google.maps.routing_v2.types.RouteTravelMode): - The travel mode used for this step. - """ - - class RouteLegStepLocalizedValues(proto.Message): - r"""Text representations of certain properties. - - Attributes: - distance (google.type.localized_text_pb2.LocalizedText): - Travel distance represented in text form. - static_duration (google.type.localized_text_pb2.LocalizedText): - Duration without taking traffic conditions - into consideration, represented in text form. - """ - - distance: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - static_duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=3, - message=localized_text_pb2.LocalizedText, - ) - - 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', - ) - localized_values: RouteLegStepLocalizedValues = proto.Field( - proto.MESSAGE, - number=8, - message=RouteLegStepLocalizedValues, - ) - transit_details: 'RouteLegStepTransitDetails' = proto.Field( - proto.MESSAGE, - number=9, - message='RouteLegStepTransitDetails', - ) - travel_mode: route_travel_mode.RouteTravelMode = proto.Field( - proto.ENUM, - number=10, - enum=route_travel_mode.RouteTravelMode, - ) - - -class RouteLegStepTransitDetails(proto.Message): - r"""Additional information for the ``RouteLegStep`` related to - ``TRANSIT`` routes. - - Attributes: - stop_details (google.maps.routing_v2.types.RouteLegStepTransitDetails.TransitStopDetails): - Information about the arrival and departure - stops for the step. - localized_values (google.maps.routing_v2.types.RouteLegStepTransitDetails.TransitDetailsLocalizedValues): - Text representations of properties of the - ``RouteLegStepTransitDetails``. - headsign (str): - Specifies the direction in which to travel on - this line as marked on the vehicle or at the - departure stop. The direction is often the - terminus station. - headway (google.protobuf.duration_pb2.Duration): - Specifies the expected time as a duration - between departures from the same stop at this - time. For example, with a headway seconds value - of 600, you would expect a ten minute wait if - you should miss your bus. - transit_line (google.maps.routing_v2.types.TransitLine): - Information about the transit line used in - this step. - stop_count (int): - The number of stops from the departure to the arrival stop. - This count includes the arrival stop, but excludes the - departure stop. For example, if your route leaves from Stop - A, passes through stops B and C, and arrives at stop D, - stop_count returns 3. - trip_short_text (str): - The text that appears in schedules and sign boards to - identify a transit trip to passengers. The text should - uniquely identify a trip within a service day. For example, - "538" is the ``trip_short_text`` of the Amtrak train that - leaves San Jose, CA at 15:10 on weekdays to Sacramento, CA. - """ - - class TransitStopDetails(proto.Message): - r"""Details about the transit stops for the ``RouteLegStep``. - - Attributes: - arrival_stop (google.maps.routing_v2.types.TransitStop): - Information about the arrival stop for the - step. - arrival_time (google.protobuf.timestamp_pb2.Timestamp): - The estimated time of arrival for the step. - departure_stop (google.maps.routing_v2.types.TransitStop): - Information about the departure stop for the - step. - departure_time (google.protobuf.timestamp_pb2.Timestamp): - The estimated time of departure for the step. - """ - - arrival_stop: transit.TransitStop = proto.Field( - proto.MESSAGE, - number=1, - message=transit.TransitStop, - ) - arrival_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - departure_stop: transit.TransitStop = proto.Field( - proto.MESSAGE, - number=3, - message=transit.TransitStop, - ) - departure_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - class TransitDetailsLocalizedValues(proto.Message): - r"""Localized descriptions of values for ``RouteTransitDetails``. - - Attributes: - arrival_time (google.maps.routing_v2.types.LocalizedTime): - Time in its formatted text representation - with a corresponding time zone. - departure_time (google.maps.routing_v2.types.LocalizedTime): - Time in its formatted text representation - with a corresponding time zone. - """ - - arrival_time: localized_time.LocalizedTime = proto.Field( - proto.MESSAGE, - number=1, - message=localized_time.LocalizedTime, - ) - departure_time: localized_time.LocalizedTime = proto.Field( - proto.MESSAGE, - number=2, - message=localized_time.LocalizedTime, - ) - - stop_details: TransitStopDetails = proto.Field( - proto.MESSAGE, - number=1, - message=TransitStopDetails, - ) - localized_values: TransitDetailsLocalizedValues = proto.Field( - proto.MESSAGE, - number=2, - message=TransitDetailsLocalizedValues, - ) - headsign: str = proto.Field( - proto.STRING, - number=3, - ) - headway: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - transit_line: transit.TransitLine = proto.Field( - proto.MESSAGE, - number=5, - message=transit.TransitLine, - ) - stop_count: int = proto.Field( - proto.INT32, - number=6, - ) - trip_short_text: str = proto.Field( - proto.STRING, - number=7, - ) - - -__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 57aa11e9666e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_label.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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. - SHORTER_DISTANCE (4): - Shorter travel distance route. This is an - experimental feature. - """ - ROUTE_LABEL_UNSPECIFIED = 0 - DEFAULT_ROUTE = 1 - DEFAULT_ROUTE_ALTERNATE = 2 - FUEL_EFFICIENT = 3 - SHORTER_DISTANCE = 4 - - -__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 a8a386928907..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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): - When set to true, avoids toll roads where reasonable, giving - preference to routes not containing toll roads. Applies only - to the ``DRIVE`` and ``TWO_WHEELER`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - avoid_highways (bool): - When set to true, avoids highways where reasonable, giving - preference to routes not containing highways. Applies only - to the ``DRIVE`` and ``TWO_WHEELER`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - avoid_ferries (bool): - When set to true, avoids ferries where reasonable, giving - preference to routes not containing ferries. Applies only to - the ``DRIVE`` and\ ``TWO_WHEELER`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - avoid_indoor (bool): - When set to true, avoids navigating indoors where - reasonable, giving preference 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 674af4e560a3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/route_travel_mode.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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. - TRANSIT (7): - Travel by public transit routes, where - available. - """ - TRAVEL_MODE_UNSPECIFIED = 0 - DRIVE = 1 - BICYCLE = 2 - WALK = 3 - TWO_WHEELER = 4 - TRANSIT = 7 - - -__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 ea00e0f72970..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routes_service.py +++ /dev/null @@ -1,732 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 traffic_model as gmr_traffic_model -from google.maps.routing_v2.types import transit_preferences as gmr_transit_preferences -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 -from google.type import localized_text_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. NOTE: You can only specify a ``departure_time`` in - the past when - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] - is set to ``TRANSIT``. Transit trips are available for up to - 7 days in the past or 100 days in the future. - arrival_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The arrival time. NOTE: Can only be set when - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] is - set to ``TRANSIT``. You can specify either - ``departure_time`` or ``arrival_time``, but not both. - Transit trips are available for up to 7 days in the past or - 100 days in the future. - 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 `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 - `Country code top-level - domains `__. - units (google.maps.routing_v2.types.Units): - Optional. Specifies the units of measure for the display - fields. These fields include 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 first origin. - optimize_waypoint_order (bool): - Optional. If set to true, the service attempts to minimize - the overall cost of the route by re-ordering the specified - intermediate waypoints. The request fails if any of the - intermediate waypoints is a ``via`` waypoint. Use - ``ComputeRoutesResponse.Routes.optimized_intermediate_waypoint_index`` - to find the new ordering. If - ``ComputeRoutesResponseroutes.optimized_intermediate_waypoint_index`` - is not requested in the ``X-Goog-FieldMask`` header, the - request fails. If ``optimize_waypoint_order`` is set to - false, - ``ComputeRoutesResponse.optimized_intermediate_waypoint_index`` - will be empty. - 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. When using this feature, look for - [``route_labels``][google.maps.routing.v2.Route.route_labels] - on the resulting routes. - 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. - traffic_model (google.maps.routing_v2.types.TrafficModel): - Optional. Specifies the assumptions to use when calculating - time in traffic. This setting affects the value returned in - the duration field in the - [``Route``][google.maps.routing.v2.Route] and - [``RouteLeg``][google.maps.routing.v2.RouteLeg] which - contains the predicted time in traffic based on historical - averages. ``TrafficModel`` is only available for requests - that have set - [``RoutingPreference``][google.maps.routing.v2.RoutingPreference] - to ``TRAFFIC_AWARE_OPTIMAL`` and - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] - to ``DRIVE``. Defaults to ``BEST_GUESS`` if traffic is - requested and ``TrafficModel`` is not specified. - transit_preferences (google.maps.routing_v2.types.TransitPreferences): - Optional. Specifies preferences that influence the route - returned for ``TRANSIT`` routes. NOTE: You can only specify - a ``transit_preferences`` when - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] - is set to ``TRANSIT``. - """ - 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. - SHORTER_DISTANCE (2): - Route with shorter travel distance. This is an experimental - feature. - - For ``DRIVE`` requests, this feature prioritizes shorter - distance over driving comfort. For example, it may prefer - local roads instead of highways, take dirt roads, cut - through parking lots, etc. This feature does not return any - maneuvers that Google Maps knows to be illegal. - - For ``BICYCLE`` and ``TWO_WHEELER`` requests, this feature - returns routes similar to those returned when you don't - specify ``requested_reference_routes``. - - This feature is not compatible with any other travel modes, - via intermediate waypoints, or ``optimize_waypoint_order``; - such requests will fail. However, you can use it with any - ``routing_preference``. - """ - REFERENCE_ROUTE_UNSPECIFIED = 0 - FUEL_EFFICIENT = 1 - SHORTER_DISTANCE = 2 - - 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). - HTML_FORMATTED_NAVIGATION_INSTRUCTIONS (4): - ```NavigationInstructions`` `__ - presented as a formatted HTML text string. This content is - meant to be read as-is. This content is for display only. Do - not programmatically parse it. - """ - EXTRA_COMPUTATION_UNSPECIFIED = 0 - TOLLS = 1 - FUEL_CONSUMPTION = 2 - TRAFFIC_ON_POLYLINE = 3 - HTML_FORMATTED_NAVIGATION_INSTRUCTIONS = 4 - - 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, - ) - arrival_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - 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, - ) - optimize_waypoint_order: bool = proto.Field( - proto.BOOL, - number=13, - ) - 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, - ) - traffic_model: gmr_traffic_model.TrafficModel = proto.Field( - proto.ENUM, - number=18, - enum=gmr_traffic_model.TrafficModel, - ) - transit_preferences: gmr_transit_preferences.TransitPreferences = proto.Field( - proto.MESSAGE, - number=20, - message=gmr_transit_preferences.TransitPreferences, - ) - - -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 sum of the number of origins + the number of - destinations specified as either ``place_id`` or - ``address`` must be no greater than 50. - - The product of number of origins × number of destinations - must be no greater than 625 in any case. - - The product of the number of origins × number of - destinations must be no greater than 100 if - routing_preference is set to ``TRAFFIC_AWARE_OPTIMAL``. - - The product of the number of origins × number of - destinations must be no greater than 100 if travel_mode - is set to ``TRANSIT``. - 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, - then this value defaults to the time that you made the - request. NOTE: You can only specify a ``departure_time`` in - the past when - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] - is set to ``TRANSIT``. - arrival_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. The arrival time. NOTE: Can only be set when - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode] - is set to ``TRANSIT``. You can specify either - ``departure_time`` or ``arrival_time``, but not both. - language_code (str): - Optional. The BCP-47 language code, such as "en-US" or - "sr-Latn". For more information, see `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 - `Country code top-level - domains `__. - units (google.maps.routing_v2.types.Units): - Optional. Specifies the units of measure for - the display fields. - 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. - traffic_model (google.maps.routing_v2.types.TrafficModel): - Optional. Specifies the assumptions to use when calculating - time in traffic. This setting affects the value returned in - the duration field in the - [RouteMatrixElement][google.maps.routing.v2.RouteMatrixElement] - which contains the predicted time in traffic based on - historical averages. - [RoutingPreference][google.maps.routing.v2.RoutingPreference] - to ``TRAFFIC_AWARE_OPTIMAL`` and - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] to - ``DRIVE``. Defaults to ``BEST_GUESS`` if traffic is - requested and ``TrafficModel`` is not specified. - transit_preferences (google.maps.routing_v2.types.TransitPreferences): - Optional. Specifies preferences that influence the route - returned for ``TRANSIT`` routes. NOTE: You can only specify - a ``transit_preferences`` when - [RouteTravelMode][google.maps.routing.v2.RouteTravelMode] is - set to ``TRANSIT``. - """ - 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, - ) - arrival_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - language_code: str = proto.Field( - proto.STRING, - number=6, - ) - region_code: str = proto.Field( - proto.STRING, - number=9, - ) - units: gmr_units.Units = proto.Field( - proto.ENUM, - number=7, - enum=gmr_units.Units, - ) - extra_computations: MutableSequence[ExtraComputation] = proto.RepeatedField( - proto.ENUM, - number=8, - enum=ExtraComputation, - ) - traffic_model: gmr_traffic_model.TrafficModel = proto.Field( - proto.ENUM, - number=10, - enum=gmr_traffic_model.TrafficModel, - ) - transit_preferences: gmr_transit_preferences.TransitPreferences = proto.Field( - proto.MESSAGE, - number=12, - message=gmr_transit_preferences.TransitPreferences, - ) - - -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"""Contains 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. - localized_values (google.maps.routing_v2.types.RouteMatrixElement.LocalizedValues): - Text representations of properties of the - ``RouteMatrixElement``. - """ - - class LocalizedValues(proto.Message): - r"""Text representations of certain properties. - - Attributes: - distance (google.type.localized_text_pb2.LocalizedText): - Travel distance represented in text form. - duration (google.type.localized_text_pb2.LocalizedText): - Duration represented in text form taking traffic conditions - into consideration. Note: If traffic information was not - requested, this value is the same value as static_duration. - static_duration (google.type.localized_text_pb2.LocalizedText): - Duration represented in text form without - taking traffic conditions into consideration. - transit_fare (google.type.localized_text_pb2.LocalizedText): - Transit fare represented in text form. - """ - - distance: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=2, - message=localized_text_pb2.LocalizedText, - ) - static_duration: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=3, - message=localized_text_pb2.LocalizedText, - ) - transit_fare: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=4, - message=localized_text_pb2.LocalizedText, - ) - - 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, - ) - localized_values: LocalizedValues = proto.Field( - proto.MESSAGE, - number=10, - message=LocalizedValues, - ) - - -__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 a0bd24974a2d..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/routing_preference.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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``, the route and duration chosen - are based on road network and average time-independent - traffic conditions, not current road conditions. - Consequently, routes may include roads that are temporarily - closed. 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 5ace8166d68d..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 c6cf129bc732..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 d0de0e8a78a8..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/toll_passes.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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. - JP_ETC (98): - Japan - ETC. Electronic wireless system to collect - tolls. https://www.go-etc.jp/ - JP_ETC2 (99): - Japan - ETC2.0. New version of ETC with further discount - and bidirectional communication between devices - on vehicles and antennas on the road. - https://www.go-etc.jp/etc2/index.html - 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. - Deprecated as this pass type no longer exists. - US_MI_IQ_TAG (95): - 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_AVI_TAG (97): - TX, 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_FUEGO_TAG (96): - 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_MOV_PASS (100): - 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 - JP_ETC = 98 - JP_ETC2 = 99 - 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_IQ_TAG = 95 - 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_AVI_TAG = 97 - 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_FUEGO_TAG = 96 - 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_MOV_PASS = 100 - 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/traffic_model.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py deleted file mode 100644 index 0f78d92f1f45..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/traffic_model.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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={ - 'TrafficModel', - }, -) - - -class TrafficModel(proto.Enum): - r"""Specifies the assumptions to use when calculating time in traffic. - This setting affects the value returned in the ``duration`` field in - the response, which contains the predicted time in traffic based on - historical averages. - - Values: - TRAFFIC_MODEL_UNSPECIFIED (0): - Unused. If specified, will default to ``BEST_GUESS``. - BEST_GUESS (1): - Indicates that the returned ``duration`` should be the best - estimate of travel time given what is known about both - historical traffic conditions and live traffic. Live traffic - becomes more important the closer the ``departure_time`` is - to now. - PESSIMISTIC (2): - Indicates that the returned duration should - be longer than the actual travel time on most - days, though occasional days with particularly - bad traffic conditions may exceed this value. - OPTIMISTIC (3): - Indicates that the returned duration should - be shorter than the actual travel time on most - days, though occasional days with particularly - good traffic conditions may be faster than this - value. - """ - TRAFFIC_MODEL_UNSPECIFIED = 0 - BEST_GUESS = 1 - PESSIMISTIC = 2 - OPTIMISTIC = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py deleted file mode 100644 index bfa6ba1e738e..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit.py +++ /dev/null @@ -1,259 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -from google.type import localized_text_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.routing.v2', - manifest={ - 'TransitAgency', - 'TransitLine', - 'TransitStop', - 'TransitVehicle', - }, -) - - -class TransitAgency(proto.Message): - r"""A transit agency that operates a transit line. - - Attributes: - name (str): - The name of this transit agency. - phone_number (str): - The transit agency's locale-specific - formatted phone number. - uri (str): - The transit agency's URI. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - phone_number: str = proto.Field( - proto.STRING, - number=2, - ) - uri: str = proto.Field( - proto.STRING, - number=3, - ) - - -class TransitLine(proto.Message): - r"""Contains information about the transit line used in this - step. - - Attributes: - agencies (MutableSequence[google.maps.routing_v2.types.TransitAgency]): - The transit agency (or agencies) that - operates this transit line. - name (str): - The full name of this transit line, For - example, "8 Avenue Local". - uri (str): - the URI for this transit line as provided by - the transit agency. - color (str): - The color commonly used in signage for this - line. Represented in hexadecimal. - icon_uri (str): - The URI for the icon associated with this - line. - name_short (str): - The short name of this transit line. This - name will normally be a line number, such as - "M7" or "355". - text_color (str): - The color commonly used in text on signage - for this line. Represented in hexadecimal. - vehicle (google.maps.routing_v2.types.TransitVehicle): - The type of vehicle that operates on this - transit line. - """ - - agencies: MutableSequence['TransitAgency'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TransitAgency', - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - uri: str = proto.Field( - proto.STRING, - number=3, - ) - color: str = proto.Field( - proto.STRING, - number=4, - ) - icon_uri: str = proto.Field( - proto.STRING, - number=5, - ) - name_short: str = proto.Field( - proto.STRING, - number=6, - ) - text_color: str = proto.Field( - proto.STRING, - number=7, - ) - vehicle: 'TransitVehicle' = proto.Field( - proto.MESSAGE, - number=8, - message='TransitVehicle', - ) - - -class TransitStop(proto.Message): - r"""Information about a transit stop. - - Attributes: - name (str): - The name of the transit stop. - location (google.maps.routing_v2.types.Location): - The location of the stop expressed in - latitude/longitude coordinates. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - location: gmr_location.Location = proto.Field( - proto.MESSAGE, - number=2, - message=gmr_location.Location, - ) - - -class TransitVehicle(proto.Message): - r"""Information about a vehicle used in transit routes. - - Attributes: - name (google.type.localized_text_pb2.LocalizedText): - The name of this vehicle, capitalized. - type_ (google.maps.routing_v2.types.TransitVehicle.TransitVehicleType): - The type of vehicle used. - icon_uri (str): - The URI for an icon associated with this - vehicle type. - local_icon_uri (str): - The URI for the icon associated with this - vehicle type, based on the local transport - signage. - """ - class TransitVehicleType(proto.Enum): - r"""The type of vehicles for transit routes. - - Values: - TRANSIT_VEHICLE_TYPE_UNSPECIFIED (0): - Unused. - BUS (1): - Bus. - CABLE_CAR (2): - A vehicle that operates on a cable, usually on the ground. - Aerial cable cars may be of the type ``GONDOLA_LIFT``. - COMMUTER_TRAIN (3): - Commuter rail. - FERRY (4): - Ferry. - FUNICULAR (5): - A vehicle that is pulled up a steep incline - by a cable. A Funicular typically consists of - two cars, with each car acting as a - counterweight for the other. - GONDOLA_LIFT (6): - An aerial cable car. - HEAVY_RAIL (7): - Heavy rail. - HIGH_SPEED_TRAIN (8): - High speed train. - INTERCITY_BUS (9): - Intercity bus. - LONG_DISTANCE_TRAIN (10): - Long distance train. - METRO_RAIL (11): - Light rail transit. - MONORAIL (12): - Monorail. - OTHER (13): - All other vehicles. - RAIL (14): - Rail. - SHARE_TAXI (15): - Share taxi is a kind of bus with the ability - to drop off and pick up passengers anywhere on - its route. - SUBWAY (16): - Underground light rail. - TRAM (17): - Above ground light rail. - TROLLEYBUS (18): - Trolleybus. - """ - TRANSIT_VEHICLE_TYPE_UNSPECIFIED = 0 - BUS = 1 - CABLE_CAR = 2 - COMMUTER_TRAIN = 3 - FERRY = 4 - FUNICULAR = 5 - GONDOLA_LIFT = 6 - HEAVY_RAIL = 7 - HIGH_SPEED_TRAIN = 8 - INTERCITY_BUS = 9 - LONG_DISTANCE_TRAIN = 10 - METRO_RAIL = 11 - MONORAIL = 12 - OTHER = 13 - RAIL = 14 - SHARE_TAXI = 15 - SUBWAY = 16 - TRAM = 17 - TROLLEYBUS = 18 - - name: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - type_: TransitVehicleType = proto.Field( - proto.ENUM, - number=2, - enum=TransitVehicleType, - ) - icon_uri: str = proto.Field( - proto.STRING, - number=3, - ) - local_icon_uri: str = proto.Field( - proto.STRING, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py b/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py deleted file mode 100644 index 7786f8811da3..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/transit_preferences.py +++ /dev/null @@ -1,97 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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={ - 'TransitPreferences', - }, -) - - -class TransitPreferences(proto.Message): - r"""Preferences for ``TRANSIT`` based routes that influence the route - that is returned. - - Attributes: - allowed_travel_modes (MutableSequence[google.maps.routing_v2.types.TransitPreferences.TransitTravelMode]): - A set of travel modes to use when getting a ``TRANSIT`` - route. Defaults to all supported modes of travel. - routing_preference (google.maps.routing_v2.types.TransitPreferences.TransitRoutingPreference): - A routing preference that, when specified, influences the - ``TRANSIT`` route returned. - """ - class TransitTravelMode(proto.Enum): - r"""A set of values used to specify the mode of transit. - - Values: - TRANSIT_TRAVEL_MODE_UNSPECIFIED (0): - No transit travel mode specified. - BUS (1): - Travel by bus. - SUBWAY (2): - Travel by subway. - TRAIN (3): - Travel by train. - LIGHT_RAIL (4): - Travel by light rail or tram. - RAIL (5): - Travel by rail. This is equivalent to a combination of - ``SUBWAY``, ``TRAIN``, and ``LIGHT_RAIL``. - """ - TRANSIT_TRAVEL_MODE_UNSPECIFIED = 0 - BUS = 1 - SUBWAY = 2 - TRAIN = 3 - LIGHT_RAIL = 4 - RAIL = 5 - - class TransitRoutingPreference(proto.Enum): - r"""Specifies routing preferences for transit routes. - - Values: - TRANSIT_ROUTING_PREFERENCE_UNSPECIFIED (0): - No preference specified. - LESS_WALKING (1): - Indicates that the calculated route should - prefer limited amounts of walking. - FEWER_TRANSFERS (2): - Indicates that the calculated route should - prefer a limited number of transfers. - """ - TRANSIT_ROUTING_PREFERENCE_UNSPECIFIED = 0 - LESS_WALKING = 1 - FEWER_TRANSFERS = 2 - - allowed_travel_modes: MutableSequence[TransitTravelMode] = proto.RepeatedField( - proto.ENUM, - number=1, - enum=TransitTravelMode, - ) - routing_preference: TransitRoutingPreference = proto.Field( - proto.ENUM, - number=2, - enum=TransitRoutingPreference, - ) - - -__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 911de7f76fd7..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 9da25c5d86d9..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 59b79853333c..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/google/maps/routing_v2/types/vehicle_info.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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"""Contains the vehicle information, such as the vehicle - emission type. - - Attributes: - emission_type (google.maps.routing_v2.types.VehicleEmissionType): - Describes the vehicle's emission type. Applies only to the - ``DRIVE`` - [``RouteTravelMode``][google.maps.routing.v2.RouteTravelMode]. - """ - - 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 d6748f9d6db3..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 b99c4c5bb684..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-maps-routing' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - 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)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - 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)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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', - '-p', - '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==7.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, - ) 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 f326b5e2134c..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 9d1e1ae87791..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ba59057436a1..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 49d835374e19..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 8c26fc095087..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', 'arrival_time', 'language_code', 'region_code', 'units', 'extra_computations', 'traffic_model', 'transit_preferences', ), - 'compute_routes': ('origin', 'destination', 'intermediates', 'travel_mode', 'routing_preference', 'polyline_quality', 'polyline_encoding', 'departure_time', 'arrival_time', 'compute_alternative_routes', 'route_modifiers', 'language_code', 'region_code', 'units', 'optimize_waypoint_order', 'requested_reference_routes', 'extra_computations', 'traffic_model', 'transit_preferences', ), - } - - 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 4336dee44a87..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re - -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 = None - -with open(os.path.join(package_root, 'google/maps/routing/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -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.1, <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.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=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", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-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.find_namespace_packages() - if package.startswith("google") -] - -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", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - 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.13.txt b/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.13.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 277853c664a0..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +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.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -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 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 7b3de3117f38..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 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 2dd1e032be26..000000000000 --- a/owl-bot-staging/google-maps-routing/v2/tests/unit/gapic/routing_v2/test_routes.py +++ /dev/null @@ -1,2328 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -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 - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -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.api_core import retry as retries -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 traffic_model -from google.maps.routing_v2.types import transit_preferences -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 - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# 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 - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -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 - -def test__read_environment_variables(): - assert RoutesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert RoutesClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert RoutesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - RoutesClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert RoutesClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert RoutesClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert RoutesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - RoutesClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert RoutesClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert RoutesClient._get_client_cert_source(None, False) is None - assert RoutesClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert RoutesClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - 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_default_cert_source): - assert RoutesClient._get_client_cert_source(None, True) is mock_default_cert_source - assert RoutesClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = RoutesClient._DEFAULT_UNIVERSE - default_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert RoutesClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert RoutesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RoutesClient.DEFAULT_MTLS_ENDPOINT - assert RoutesClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert RoutesClient._get_api_endpoint(None, None, default_universe, "always") == RoutesClient.DEFAULT_MTLS_ENDPOINT - assert RoutesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RoutesClient.DEFAULT_MTLS_ENDPOINT - assert RoutesClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert RoutesClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - RoutesClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert RoutesClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert RoutesClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert RoutesClient._get_universe_domain(None, None) == RoutesClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - RoutesClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@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_TEMPLATE", modify_default_endpoint_template(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE", modify_default_endpoint_template(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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 - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - RoutesClient, RoutesAsyncClient -]) -@mock.patch.object(RoutesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesClient)) -@mock.patch.object(RoutesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RoutesAsyncClient)) -def test_routes_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = RoutesClient._DEFAULT_UNIVERSE - default_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RoutesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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] - request = routes_service.ComputeRoutesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, routes_service.ComputeRoutesResponse) - - -def test_compute_routes_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = routes_service.ComputeRoutesRequest( - language_code='language_code_value', - region_code='region_code_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.compute_routes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRoutesRequest( - language_code='language_code_value', - region_code='region_code_value', - ) - -def test_compute_routes_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.compute_routes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.compute_routes] = mock_rpc - request = {} - client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.compute_routes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_compute_routes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = RoutesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.compute_routes in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.compute_routes] = mock_rpc - - request = {} - await client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.compute_routes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_compute_routes_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRoutesRequest): - client = RoutesAsyncClient( - credentials=async_anonymous_credentials(), - 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] - request = routes_service.ComputeRoutesRequest() - assert args[0] == request - - # 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] - request = routes_service.ComputeRouteMatrixRequest() - assert args[0] == request - - # 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_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = routes_service.ComputeRouteMatrixRequest( - language_code='language_code_value', - region_code='region_code_value', - ) - - # 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: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.compute_route_matrix(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == routes_service.ComputeRouteMatrixRequest( - language_code='language_code_value', - region_code='region_code_value', - ) - -def test_compute_route_matrix_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.compute_route_matrix in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.compute_route_matrix] = mock_rpc - request = {} - client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.compute_route_matrix(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_compute_route_matrix_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = RoutesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.compute_route_matrix in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.compute_route_matrix] = mock_rpc - - request = {} - await client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.compute_route_matrix(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_compute_route_matrix_async(transport: str = 'grpc_asyncio', request_type=routes_service.ComputeRouteMatrixRequest): - client = RoutesAsyncClient( - credentials=async_anonymous_credentials(), - 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] - request = routes_service.ComputeRouteMatrixRequest() - assert args[0] == request - - # 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) - - -def test_compute_routes_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.compute_routes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.compute_routes] = mock_rpc - - request = {} - client.compute_routes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.compute_routes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -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, - 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 - - # Convert return value to protobuf type - return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(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", ))) - - -def test_compute_route_matrix_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.compute_route_matrix in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.compute_route_matrix] = mock_rpc - - request = {} - client.compute_route_matrix(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.compute_route_matrix(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -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, - 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 - - # Convert return value to protobuf type - return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(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", ))) - - -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 = client_options.ClientOptions() - 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() - -def test_transport_kind_grpc(): - transport = RoutesClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_compute_routes_empty_call_grpc(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - call.return_value = routes_service.ComputeRoutesResponse() - client.compute_routes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRoutesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_compute_route_matrix_empty_call_grpc(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - call.return_value = iter([routes_service.RouteMatrixElement()]) - client.compute_route_matrix(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRouteMatrixRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = RoutesAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = RoutesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_compute_routes_empty_call_grpc_asyncio(): - client = RoutesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, 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( - )) - await client.compute_routes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRoutesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_compute_route_matrix_empty_call_grpc_asyncio(): - client = RoutesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, 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()]) - await client.compute_route_matrix(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRouteMatrixRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = RoutesClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_compute_routes_rest_bad_request(request_type=routes_service.ComputeRoutesRequest): - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.compute_routes(request) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRoutesRequest, - dict, -]) -def test_compute_routes_rest_call_success(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 = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = routes_service.ComputeRoutesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(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) - - -@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 = mock.Mock() - req.return_value.status_code = 200 - return_value = routes_service.ComputeRoutesResponse.to_json(routes_service.ComputeRoutesResponse()) - req.return_value.content = return_value - - 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_route_matrix_rest_bad_request(request_type=routes_service.ComputeRouteMatrixRequest): - 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 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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.compute_route_matrix(request) - - -@pytest.mark.parametrize("request_type", [ - routes_service.ComputeRouteMatrixRequest, - dict, -]) -def test_compute_route_matrix_rest_call_success(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 = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = routes_service.RouteMatrixElement.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - json_return_value = "[{}]".format(json_return_value) - response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) - req.return_value = response_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 - - -@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 = mock.Mock() - req.return_value.status_code = 200 - return_value = routes_service.RouteMatrixElement.to_json(routes_service.RouteMatrixElement()) - req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) - - 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_initialize_client_w_rest(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_compute_routes_empty_call_rest(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_routes), - '__call__') as call: - client.compute_routes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRoutesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_compute_route_matrix_empty_call_rest(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.compute_route_matrix), - '__call__') as call: - client.compute_route_matrix(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = routes_service.ComputeRouteMatrixRequest() - - assert args[0] == request_msg - - -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) - - -def test_transport_close_grpc(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = RoutesAsyncClient( - credentials=async_anonymous_credentials(), - 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_rest(): - client = RoutesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - 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/gapic_version.py b/packages/google-maps-routing/google/maps/routing/gapic_version.py index 44e5c049e336..558c8aab67c5 100644 --- a/packages/google-maps-routing/google/maps/routing/gapic_version.py +++ b/packages/google-maps-routing/google/maps/routing/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.12" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-routing/google/maps/routing_v2/gapic_version.py b/packages/google-maps-routing/google/maps/routing_v2/gapic_version.py index 44e5c049e336..558c8aab67c5 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/gapic_version.py +++ b/packages/google-maps-routing/google/maps/routing_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.12" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} 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 c511e031d0d9..a1f0286ea2bf 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 @@ -110,15 +110,16 @@ class Route(proto.Message): localized_values (google.maps.routing_v2.types.Route.RouteLocalizedValues): Text representations of properties of the ``Route``. route_token (str): - A web-safe, base64-encoded route token that can be passed to - the Navigation SDK, that allows the Navigation SDK to - reconstruct the route during navigation, and, in the event - of rerouting, honor the original intention when you created - the route by calling ComputeRoutes. Customers should treat - this token as an opaque blob. It is not meant for reading or - mutating. NOTE: ``Route.route_token`` is only available for - requests that have set - ``ComputeRoutesRequest.routing_preference`` to + An opaque token that can be passed to `Navigation + SDK `__ + to reconstruct the route during navigation, and, in the + event of rerouting, honor the original intention when the + route was created. Treat this token as an opaque blob. Don't + compare its value across requests as its value may change + even if the service returns the exact same route. + + 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 not supported for requests that have Via waypoints. @@ -131,9 +132,10 @@ class RouteLocalizedValues(proto.Message): distance (google.type.localized_text_pb2.LocalizedText): Travel distance represented in text form. duration (google.type.localized_text_pb2.LocalizedText): - Duration taking traffic conditions into consideration, - represented in text form. Note: If you did not request - traffic information, this value will be the same value as + Duration, represented in text form and localized to the + region of the query. Takes traffic conditions into + consideration. Note: If you did not request traffic + information, this value is the same value as ``static_duration``. static_duration (google.type.localized_text_pb2.LocalizedText): Duration without taking traffic conditions @@ -408,9 +410,10 @@ class RouteLegLocalizedValues(proto.Message): distance (google.type.localized_text_pb2.LocalizedText): Travel distance represented in text form. duration (google.type.localized_text_pb2.LocalizedText): - Duration taking traffic conditions into consideration - represented in text form. Note: If you did not request - traffic information, this value will be the same value as + Duration, represented in text form and localized to the + region of the query. Takes traffic conditions into + consideration. Note: If you did not request traffic + information, this value is the same value as static_duration. static_duration (google.type.localized_text_pb2.LocalizedText): Duration without taking traffic conditions @@ -695,7 +698,7 @@ class RouteLegStepTransitDetails(proto.Message): This count includes the arrival stop, but excludes the departure stop. For example, if your route leaves from Stop A, passes through stops B and C, and arrives at stop D, - stop_count will return 3. + stop_count returns 3. trip_short_text (str): The text that appears in schedules and sign boards to identify a transit trip to passengers. The text should 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 4d78bcc978cd..b72d12e4877d 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 @@ -47,11 +47,15 @@ class RouteLabel(proto.Enum): Fuel efficient route. Routes labeled with this value are determined to be optimized for Eco parameters such as fuel consumption. + SHORTER_DISTANCE (4): + Shorter travel distance route. This is an + experimental feature. """ ROUTE_LABEL_UNSPECIFIED = 0 DEFAULT_ROUTE = 1 DEFAULT_ROUTE_ALTERNATE = 2 FUEL_EFFICIENT = 3 + SHORTER_DISTANCE = 4 __all__ = tuple(sorted(__protobuf__.manifest)) 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 c71da30566bb..02becc425942 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 @@ -161,7 +161,9 @@ class ComputeRoutesRequest(proto.Message): 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. + fuel efficient route. When using this feature, look for + [``route_labels``][google.maps.routing.v2.Route.route_labels] + on the resulting routes. 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 @@ -199,12 +201,29 @@ class ReferenceRoute(proto.Enum): 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. + Fuel efficient route. + SHORTER_DISTANCE (2): + Route with shorter travel distance. This is an experimental + feature. + + For ``DRIVE`` requests, this feature prioritizes shorter + distance over driving comfort. For example, it may prefer + local roads instead of highways, take dirt roads, cut + through parking lots, etc. This feature does not return any + maneuvers that Google Maps knows to be illegal. + + For ``BICYCLE`` and ``TWO_WHEELER`` requests, this feature + returns routes similar to those returned when you don't + specify ``requested_reference_routes``. + + This feature is not compatible with any other travel modes, + via intermediate waypoints, or ``optimize_waypoint_order``; + such requests will fail. However, you can use it with any + ``routing_preference``. """ REFERENCE_ROUTE_UNSPECIFIED = 0 FUEL_EFFICIENT = 1 + SHORTER_DISTANCE = 2 class ExtraComputation(proto.Enum): r"""Extra computations to perform while completing the request. diff --git a/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json index ecfe37970694..b5ed5aca319c 100644 --- a/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json +++ b/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-routing", - "version": "0.6.12" + "version": "0.1.0" }, "snippets": [ {