From bf4542fe61a249a1ffc5b8fc012cfb5cd662f475 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 9 Dec 2024 23:58:29 +0000 Subject: [PATCH 1/2] docs: correct SearchVehiclesRequest.ordered_by description PiperOrigin-RevId: 704403622 Source-Link: https://github.com/googleapis/googleapis/commit/4e78e682efabbe91a3bc62d3ce0213f02524929d Source-Link: https://github.com/googleapis/googleapis-gen/commit/157433126b3c6546254d9f8c3785b0af19b9d7bc Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtZmxlZXRlbmdpbmUvLk93bEJvdC55YW1sIiwiaCI6IjE1NzQzMzEyNmIzYzY1NDYyNTRkOWY4YzM3ODViMGFmMTliOWQ3YmMifQ== --- .../google-maps-fleetengine/v1/.coveragerc | 13 + .../google-maps-fleetengine/v1/.flake8 | 33 + .../google-maps-fleetengine/v1/MANIFEST.in | 2 + .../google-maps-fleetengine/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../google-maps-fleetengine/v1/docs/conf.py | 376 ++ .../v1/docs/fleetengine_v1/services_.rst | 7 + .../v1/docs/fleetengine_v1/trip_service.rst | 10 + .../v1/docs/fleetengine_v1/types_.rst | 6 + .../docs/fleetengine_v1/vehicle_service.rst | 10 + .../google-maps-fleetengine/v1/docs/index.rst | 7 + .../v1/google/maps/fleetengine/__init__.py | 123 + .../google/maps/fleetengine/gapic_version.py | 16 + .../v1/google/maps/fleetengine/py.typed | 2 + .../v1/google/maps/fleetengine_v1/__init__.py | 124 + .../maps/fleetengine_v1/gapic_metadata.json | 147 + .../maps/fleetengine_v1/gapic_version.py | 16 + .../v1/google/maps/fleetengine_v1/py.typed | 2 + .../maps/fleetengine_v1/services/__init__.py | 15 + .../services/trip_service/__init__.py | 22 + .../services/trip_service/async_client.py | 675 ++++ .../services/trip_service/client.py | 1003 +++++ .../services/trip_service/pagers.py | 163 + .../trip_service/transports/README.rst | 9 + .../trip_service/transports/__init__.py | 33 + .../services/trip_service/transports/base.py | 248 ++ .../services/trip_service/transports/grpc.py | 377 ++ .../trip_service/transports/grpc_asyncio.py | 454 +++ .../services/vehicle_service/__init__.py | 22 + .../services/vehicle_service/async_client.py | 827 +++++ .../services/vehicle_service/client.py | 1155 ++++++ .../services/vehicle_service/pagers.py | 163 + .../vehicle_service/transports/README.rst | 9 + .../vehicle_service/transports/__init__.py | 33 + .../vehicle_service/transports/base.py | 270 ++ .../vehicle_service/transports/grpc.py | 455 +++ .../transports/grpc_asyncio.py | 546 +++ .../maps/fleetengine_v1/types/__init__.py | 124 + .../maps/fleetengine_v1/types/fleetengine.py | 628 ++++ .../maps/fleetengine_v1/types/header.py | 168 + .../maps/fleetengine_v1/types/traffic.py | 108 + .../maps/fleetengine_v1/types/trip_api.py | 460 +++ .../google/maps/fleetengine_v1/types/trips.py | 490 +++ .../maps/fleetengine_v1/types/vehicle_api.py | 1047 ++++++ .../maps/fleetengine_v1/types/vehicles.py | 580 +++ .../google-maps-fleetengine/v1/mypy.ini | 3 + .../google-maps-fleetengine/v1/noxfile.py | 280 ++ ...enerated_trip_service_create_trip_async.py | 53 + ...generated_trip_service_create_trip_sync.py | 53 + ...1_generated_trip_service_get_trip_async.py | 52 + ...v1_generated_trip_service_get_trip_sync.py | 52 + ...trip_service_report_billable_trip_async.py | 51 + ..._trip_service_report_billable_trip_sync.py | 51 + ...nerated_trip_service_search_trips_async.py | 53 + ...enerated_trip_service_search_trips_sync.py | 53 + ...enerated_trip_service_update_trip_async.py | 52 + ...generated_trip_service_update_trip_sync.py | 52 + ...ed_vehicle_service_create_vehicle_async.py | 53 + ...ted_vehicle_service_create_vehicle_sync.py | 53 + ...rated_vehicle_service_get_vehicle_async.py | 52 + ...erated_vehicle_service_get_vehicle_sync.py | 52 + ...ted_vehicle_service_list_vehicles_async.py | 54 + ...ated_vehicle_service_list_vehicles_sync.py | 54 + ...d_vehicle_service_search_vehicles_async.py | 57 + ...ed_vehicle_service_search_vehicles_sync.py | 57 + ...ed_vehicle_service_update_vehicle_async.py | 52 + ...service_update_vehicle_attributes_async.py | 56 + ..._service_update_vehicle_attributes_sync.py | 56 + ...ted_vehicle_service_update_vehicle_sync.py | 52 + .../snippet_metadata_maps.fleetengine.v1.json | 1692 +++++++++ .../scripts/fixup_fleetengine_v1_keywords.py | 186 + .../google-maps-fleetengine/v1/setup.py | 99 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.13.txt | 7 + .../v1/testing/constraints-3.7.txt | 11 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/fleetengine_v1/__init__.py | 16 + .../gapic/fleetengine_v1/test_trip_service.py | 3025 +++++++++++++++ .../fleetengine_v1/test_vehicle_service.py | 3280 +++++++++++++++++ 85 files changed, 20882 insertions(+) create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/.coveragerc create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/.flake8 create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/README.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/conf.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/mypy.ini create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/noxfile.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/setup.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py create mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py diff --git a/owl-bot-staging/google-maps-fleetengine/v1/.coveragerc b/owl-bot-staging/google-maps-fleetengine/v1/.coveragerc new file mode 100644 index 000000000000..2611031f9d9f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/fleetengine/__init__.py + google/maps/fleetengine/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-fleetengine/v1/.flake8 b/owl-bot-staging/google-maps-fleetengine/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/.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-fleetengine/v1/MANIFEST.in b/owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in new file mode 100644 index 000000000000..3dcb3007a4fb --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/maps/fleetengine *.py +recursive-include google/maps/fleetengine_v1 *.py diff --git a/owl-bot-staging/google-maps-fleetengine/v1/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/README.rst new file mode 100644 index 000000000000..b9bd958ce86c --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Maps Fleetengine 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 Fleetengine 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-fleetengine/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-fleetengine/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/conf.py b/owl-bot-staging/google-maps-fleetengine/v1/docs/conf.py new file mode 100644 index 000000000000..de2c2c6df868 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine 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-fleetengine" +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-fleetengine-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-fleetengine.tex", + u"google-maps-fleetengine 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-fleetengine", + u"Google Maps Fleetengine 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-fleetengine", + u"google-maps-fleetengine Documentation", + author, + "google-maps-fleetengine", + "GAPIC library for Google Maps Fleetengine 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-fleetengine/v1/docs/fleetengine_v1/services_.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst new file mode 100644 index 000000000000..a23a0eb62775 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst @@ -0,0 +1,7 @@ +Services for Google Maps Fleetengine v1 API +=========================================== +.. toctree:: + :maxdepth: 2 + + trip_service + vehicle_service diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst new file mode 100644 index 000000000000..9cb42aff9bcf --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst @@ -0,0 +1,10 @@ +TripService +----------------------------- + +.. automodule:: google.maps.fleetengine_v1.services.trip_service + :members: + :inherited-members: + +.. automodule:: google.maps.fleetengine_v1.services.trip_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst new file mode 100644 index 000000000000..2e980bba2916 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Fleetengine v1 API +======================================== + +.. automodule:: google.maps.fleetengine_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst new file mode 100644 index 000000000000..e1bfe924fcca --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst @@ -0,0 +1,10 @@ +VehicleService +-------------------------------- + +.. automodule:: google.maps.fleetengine_v1.services.vehicle_service + :members: + :inherited-members: + +.. automodule:: google.maps.fleetengine_v1.services.vehicle_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst new file mode 100644 index 000000000000..2b0090bf63a3 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + fleetengine_v1/services_ + fleetengine_v1/types_ diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py new file mode 100644 index 000000000000..474efa60eda8 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py @@ -0,0 +1,123 @@ +# -*- 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.fleetengine import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.fleetengine_v1.services.trip_service.client import TripServiceClient +from google.maps.fleetengine_v1.services.trip_service.async_client import TripServiceAsyncClient +from google.maps.fleetengine_v1.services.vehicle_service.client import VehicleServiceClient +from google.maps.fleetengine_v1.services.vehicle_service.async_client import VehicleServiceAsyncClient + +from google.maps.fleetengine_v1.types.fleetengine import TerminalLocation +from google.maps.fleetengine_v1.types.fleetengine import TerminalPointId +from google.maps.fleetengine_v1.types.fleetengine import TripWaypoint +from google.maps.fleetengine_v1.types.fleetengine import VehicleAttribute +from google.maps.fleetengine_v1.types.fleetengine import VehicleLocation +from google.maps.fleetengine_v1.types.fleetengine import LocationSensor +from google.maps.fleetengine_v1.types.fleetengine import NavigationStatus +from google.maps.fleetengine_v1.types.fleetengine import PolylineFormatType +from google.maps.fleetengine_v1.types.fleetengine import TripType +from google.maps.fleetengine_v1.types.fleetengine import WaypointType +from google.maps.fleetengine_v1.types.header import RequestHeader +from google.maps.fleetengine_v1.types.traffic import ConsumableTrafficPolyline +from google.maps.fleetengine_v1.types.traffic import SpeedReadingInterval +from google.maps.fleetengine_v1.types.trip_api import CreateTripRequest +from google.maps.fleetengine_v1.types.trip_api import GetTripRequest +from google.maps.fleetengine_v1.types.trip_api import ReportBillableTripRequest +from google.maps.fleetengine_v1.types.trip_api import SearchTripsRequest +from google.maps.fleetengine_v1.types.trip_api import SearchTripsResponse +from google.maps.fleetengine_v1.types.trip_api import UpdateTripRequest +from google.maps.fleetengine_v1.types.trips import StopLocation +from google.maps.fleetengine_v1.types.trips import Trip +from google.maps.fleetengine_v1.types.trips import BillingPlatformIdentifier +from google.maps.fleetengine_v1.types.trips import TripStatus +from google.maps.fleetengine_v1.types.trips import TripView +from google.maps.fleetengine_v1.types.vehicle_api import CreateVehicleRequest +from google.maps.fleetengine_v1.types.vehicle_api import GetVehicleRequest +from google.maps.fleetengine_v1.types.vehicle_api import ListVehiclesRequest +from google.maps.fleetengine_v1.types.vehicle_api import ListVehiclesResponse +from google.maps.fleetengine_v1.types.vehicle_api import SearchVehiclesRequest +from google.maps.fleetengine_v1.types.vehicle_api import SearchVehiclesResponse +from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleAttributesRequest +from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleAttributesResponse +from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleRequest +from google.maps.fleetengine_v1.types.vehicle_api import VehicleAttributeList +from google.maps.fleetengine_v1.types.vehicle_api import VehicleMatch +from google.maps.fleetengine_v1.types.vehicle_api import Waypoint +from google.maps.fleetengine_v1.types.vehicles import BatteryInfo +from google.maps.fleetengine_v1.types.vehicles import DeviceSettings +from google.maps.fleetengine_v1.types.vehicles import LicensePlate +from google.maps.fleetengine_v1.types.vehicles import TrafficPolylineData +from google.maps.fleetengine_v1.types.vehicles import Vehicle +from google.maps.fleetengine_v1.types.vehicles import VisualTrafficReportPolylineRendering +from google.maps.fleetengine_v1.types.vehicles import BatteryStatus +from google.maps.fleetengine_v1.types.vehicles import LocationPowerSaveMode +from google.maps.fleetengine_v1.types.vehicles import PowerSource +from google.maps.fleetengine_v1.types.vehicles import VehicleState + +__all__ = ('TripServiceClient', + 'TripServiceAsyncClient', + 'VehicleServiceClient', + 'VehicleServiceAsyncClient', + 'TerminalLocation', + 'TerminalPointId', + 'TripWaypoint', + 'VehicleAttribute', + 'VehicleLocation', + 'LocationSensor', + 'NavigationStatus', + 'PolylineFormatType', + 'TripType', + 'WaypointType', + 'RequestHeader', + 'ConsumableTrafficPolyline', + 'SpeedReadingInterval', + 'CreateTripRequest', + 'GetTripRequest', + 'ReportBillableTripRequest', + 'SearchTripsRequest', + 'SearchTripsResponse', + 'UpdateTripRequest', + 'StopLocation', + 'Trip', + 'BillingPlatformIdentifier', + 'TripStatus', + 'TripView', + 'CreateVehicleRequest', + 'GetVehicleRequest', + 'ListVehiclesRequest', + 'ListVehiclesResponse', + 'SearchVehiclesRequest', + 'SearchVehiclesResponse', + 'UpdateVehicleAttributesRequest', + 'UpdateVehicleAttributesResponse', + 'UpdateVehicleRequest', + 'VehicleAttributeList', + 'VehicleMatch', + 'Waypoint', + 'BatteryInfo', + 'DeviceSettings', + 'LicensePlate', + 'TrafficPolylineData', + 'Vehicle', + 'VisualTrafficReportPolylineRendering', + 'BatteryStatus', + 'LocationPowerSaveMode', + 'PowerSource', + 'VehicleState', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/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-fleetengine/v1/google/maps/fleetengine/py.typed b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed new file mode 100644 index 000000000000..47d8e9910cb6 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-fleetengine package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py new file mode 100644 index 000000000000..74f5cd53382b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py @@ -0,0 +1,124 @@ +# -*- 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.fleetengine_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.trip_service import TripServiceClient +from .services.trip_service import TripServiceAsyncClient +from .services.vehicle_service import VehicleServiceClient +from .services.vehicle_service import VehicleServiceAsyncClient + +from .types.fleetengine import TerminalLocation +from .types.fleetengine import TerminalPointId +from .types.fleetengine import TripWaypoint +from .types.fleetengine import VehicleAttribute +from .types.fleetengine import VehicleLocation +from .types.fleetengine import LocationSensor +from .types.fleetengine import NavigationStatus +from .types.fleetengine import PolylineFormatType +from .types.fleetengine import TripType +from .types.fleetengine import WaypointType +from .types.header import RequestHeader +from .types.traffic import ConsumableTrafficPolyline +from .types.traffic import SpeedReadingInterval +from .types.trip_api import CreateTripRequest +from .types.trip_api import GetTripRequest +from .types.trip_api import ReportBillableTripRequest +from .types.trip_api import SearchTripsRequest +from .types.trip_api import SearchTripsResponse +from .types.trip_api import UpdateTripRequest +from .types.trips import StopLocation +from .types.trips import Trip +from .types.trips import BillingPlatformIdentifier +from .types.trips import TripStatus +from .types.trips import TripView +from .types.vehicle_api import CreateVehicleRequest +from .types.vehicle_api import GetVehicleRequest +from .types.vehicle_api import ListVehiclesRequest +from .types.vehicle_api import ListVehiclesResponse +from .types.vehicle_api import SearchVehiclesRequest +from .types.vehicle_api import SearchVehiclesResponse +from .types.vehicle_api import UpdateVehicleAttributesRequest +from .types.vehicle_api import UpdateVehicleAttributesResponse +from .types.vehicle_api import UpdateVehicleRequest +from .types.vehicle_api import VehicleAttributeList +from .types.vehicle_api import VehicleMatch +from .types.vehicle_api import Waypoint +from .types.vehicles import BatteryInfo +from .types.vehicles import DeviceSettings +from .types.vehicles import LicensePlate +from .types.vehicles import TrafficPolylineData +from .types.vehicles import Vehicle +from .types.vehicles import VisualTrafficReportPolylineRendering +from .types.vehicles import BatteryStatus +from .types.vehicles import LocationPowerSaveMode +from .types.vehicles import PowerSource +from .types.vehicles import VehicleState + +__all__ = ( + 'TripServiceAsyncClient', + 'VehicleServiceAsyncClient', +'BatteryInfo', +'BatteryStatus', +'BillingPlatformIdentifier', +'ConsumableTrafficPolyline', +'CreateTripRequest', +'CreateVehicleRequest', +'DeviceSettings', +'GetTripRequest', +'GetVehicleRequest', +'LicensePlate', +'ListVehiclesRequest', +'ListVehiclesResponse', +'LocationPowerSaveMode', +'LocationSensor', +'NavigationStatus', +'PolylineFormatType', +'PowerSource', +'ReportBillableTripRequest', +'RequestHeader', +'SearchTripsRequest', +'SearchTripsResponse', +'SearchVehiclesRequest', +'SearchVehiclesResponse', +'SpeedReadingInterval', +'StopLocation', +'TerminalLocation', +'TerminalPointId', +'TrafficPolylineData', +'Trip', +'TripServiceClient', +'TripStatus', +'TripType', +'TripView', +'TripWaypoint', +'UpdateTripRequest', +'UpdateVehicleAttributesRequest', +'UpdateVehicleAttributesResponse', +'UpdateVehicleRequest', +'Vehicle', +'VehicleAttribute', +'VehicleAttributeList', +'VehicleLocation', +'VehicleMatch', +'VehicleServiceClient', +'VehicleState', +'VisualTrafficReportPolylineRendering', +'Waypoint', +'WaypointType', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json new file mode 100644 index 000000000000..1a6ac8f7d116 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json @@ -0,0 +1,147 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.fleetengine_v1", + "protoPackage": "maps.fleetengine.v1", + "schema": "1.0", + "services": { + "TripService": { + "clients": { + "grpc": { + "libraryClient": "TripServiceClient", + "rpcs": { + "CreateTrip": { + "methods": [ + "create_trip" + ] + }, + "GetTrip": { + "methods": [ + "get_trip" + ] + }, + "ReportBillableTrip": { + "methods": [ + "report_billable_trip" + ] + }, + "SearchTrips": { + "methods": [ + "search_trips" + ] + }, + "UpdateTrip": { + "methods": [ + "update_trip" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TripServiceAsyncClient", + "rpcs": { + "CreateTrip": { + "methods": [ + "create_trip" + ] + }, + "GetTrip": { + "methods": [ + "get_trip" + ] + }, + "ReportBillableTrip": { + "methods": [ + "report_billable_trip" + ] + }, + "SearchTrips": { + "methods": [ + "search_trips" + ] + }, + "UpdateTrip": { + "methods": [ + "update_trip" + ] + } + } + } + } + }, + "VehicleService": { + "clients": { + "grpc": { + "libraryClient": "VehicleServiceClient", + "rpcs": { + "CreateVehicle": { + "methods": [ + "create_vehicle" + ] + }, + "GetVehicle": { + "methods": [ + "get_vehicle" + ] + }, + "ListVehicles": { + "methods": [ + "list_vehicles" + ] + }, + "SearchVehicles": { + "methods": [ + "search_vehicles" + ] + }, + "UpdateVehicle": { + "methods": [ + "update_vehicle" + ] + }, + "UpdateVehicleAttributes": { + "methods": [ + "update_vehicle_attributes" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VehicleServiceAsyncClient", + "rpcs": { + "CreateVehicle": { + "methods": [ + "create_vehicle" + ] + }, + "GetVehicle": { + "methods": [ + "get_vehicle" + ] + }, + "ListVehicles": { + "methods": [ + "list_vehicles" + ] + }, + "SearchVehicles": { + "methods": [ + "search_vehicles" + ] + }, + "UpdateVehicle": { + "methods": [ + "update_vehicle" + ] + }, + "UpdateVehicleAttributes": { + "methods": [ + "update_vehicle_attributes" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/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-fleetengine/v1/google/maps/fleetengine_v1/py.typed b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed new file mode 100644 index 000000000000..47d8e9910cb6 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-fleetengine package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/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-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py new file mode 100644 index 000000000000..268b90139486 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__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 TripServiceClient +from .async_client import TripServiceAsyncClient + +__all__ = ( + 'TripServiceClient', + 'TripServiceAsyncClient', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py new file mode 100644 index 000000000000..f32fa72743e2 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py @@ -0,0 +1,675 @@ +# -*- 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, Sequence, Tuple, Type, Union + +from google.maps.fleetengine_v1 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.fleetengine_v1.services.trip_service import pagers +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import traffic +from google.maps.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +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.type import latlng_pb2 # type: ignore +from .transports.base import TripServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TripServiceGrpcAsyncIOTransport +from .client import TripServiceClient + + +class TripServiceAsyncClient: + """Trip management service.""" + + _client: TripServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = TripServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TripServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = TripServiceClient._DEFAULT_UNIVERSE + + trip_path = staticmethod(TripServiceClient.trip_path) + parse_trip_path = staticmethod(TripServiceClient.parse_trip_path) + common_billing_account_path = staticmethod(TripServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TripServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TripServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(TripServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(TripServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(TripServiceClient.parse_common_organization_path) + common_project_path = staticmethod(TripServiceClient.common_project_path) + parse_common_project_path = staticmethod(TripServiceClient.parse_common_project_path) + common_location_path = staticmethod(TripServiceClient.common_location_path) + parse_common_location_path = staticmethod(TripServiceClient.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: + TripServiceAsyncClient: The constructed client. + """ + return TripServiceClient.from_service_account_info.__func__(TripServiceAsyncClient, 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: + TripServiceAsyncClient: The constructed client. + """ + return TripServiceClient.from_service_account_file.__func__(TripServiceAsyncClient, 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 TripServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TripServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TripServiceTransport: 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 = TripServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, TripServiceTransport, Callable[..., TripServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the trip service 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,TripServiceTransport,Callable[..., TripServiceTransport]]]): + 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 TripServiceTransport 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 = TripServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_trip(self, + request: Optional[Union[trip_api.CreateTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Creates a trip in the Fleet Engine and returns the + new trip. + + .. 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 fleetengine_v1 + + async def sample_create_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateTripRequest( + parent="parent_value", + trip_id="trip_id_value", + ) + + # Make the request + response = await client.create_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.CreateTripRequest, dict]]): + The request object. CreateTrip 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.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.CreateTripRequest): + request = trip_api.CreateTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 + + async def get_trip(self, + request: Optional[Union[trip_api.GetTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Get information about a single trip. + + .. 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 fleetengine_v1 + + async def sample_get_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetTripRequest( + name="name_value", + ) + + # Make the request + response = await client.get_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.GetTripRequest, dict]]): + The request object. GetTrip 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.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.GetTripRequest): + request = trip_api.GetTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 + + async def report_billable_trip(self, + request: Optional[Union[trip_api.ReportBillableTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Report billable trip usage. + + .. 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 fleetengine_v1 + + async def sample_report_billable_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.ReportBillableTripRequest( + name="name_value", + country_code="country_code_value", + ) + + # Make the request + await client.report_billable_trip(request=request) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.ReportBillableTripRequest, dict]]): + The request object. ReportBillableTrip 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. + """ + # 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, trip_api.ReportBillableTripRequest): + request = trip_api.ReportBillableTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.report_billable_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def search_trips(self, + request: Optional[Union[trip_api.SearchTripsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchTripsAsyncPager: + r"""Get all the trips for a specific vehicle. + + .. 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 fleetengine_v1 + + async def sample_search_trips(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchTripsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.search_trips(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.SearchTripsRequest, dict]]): + The request object. SearchTrips 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.fleetengine_v1.services.trip_service.pagers.SearchTripsAsyncPager: + SearchTrips response message. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # 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, trip_api.SearchTripsRequest): + request = trip_api.SearchTripsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.search_trips] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.SearchTripsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_trip(self, + request: Optional[Union[trip_api.UpdateTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Updates trip data. + + .. 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 fleetengine_v1 + + async def sample_update_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateTripRequest( + name="name_value", + ) + + # Make the request + response = await client.update_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.UpdateTripRequest, dict]]): + The request object. UpdateTrip 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.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.UpdateTripRequest): + request = trip_api.UpdateTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 + + async def __aenter__(self) -> "TripServiceAsyncClient": + 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__ = ( + "TripServiceAsyncClient", +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py new file mode 100644 index 000000000000..f2b473dd70b3 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py @@ -0,0 +1,1003 @@ +# -*- 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, Sequence, Tuple, Type, Union, cast +import warnings + +from google.maps.fleetengine_v1 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.fleetengine_v1.services.trip_service import pagers +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import traffic +from google.maps.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +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.type import latlng_pb2 # type: ignore +from .transports.base import TripServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TripServiceGrpcTransport +from .transports.grpc_asyncio import TripServiceGrpcAsyncIOTransport + + +class TripServiceClientMeta(type): + """Metaclass for the TripService 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[TripServiceTransport]] + _transport_registry["grpc"] = TripServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TripServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[TripServiceTransport]: + """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 TripServiceClient(metaclass=TripServiceClientMeta): + """Trip management service.""" + + @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 = "fleetengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "fleetengine.{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: + TripServiceClient: 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: + TripServiceClient: 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) -> TripServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TripServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def trip_path(provider: str,trip: str,) -> str: + """Returns a fully-qualified trip string.""" + return "providers/{provider}/trips/{trip}".format(provider=provider, trip=trip, ) + + @staticmethod + def parse_trip_path(path: str) -> Dict[str,str]: + """Parses a trip path into its component segments.""" + m = re.match(r"^providers/(?P.+?)/trips/(?P.+?)$", path) + return m.groupdict() if m else {} + + @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 = TripServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = TripServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = TripServiceClient._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 = TripServiceClient._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, TripServiceTransport, Callable[..., TripServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the trip service 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,TripServiceTransport,Callable[..., TripServiceTransport]]]): + 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 TripServiceTransport 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 = TripServiceClient._read_environment_variables() + self._client_cert_source = TripServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = TripServiceClient._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, TripServiceTransport) + if transport_provided: + # transport is a TripServiceTransport 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(TripServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + TripServiceClient._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[TripServiceTransport], Callable[..., TripServiceTransport]] = ( + TripServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., TripServiceTransport], 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 create_trip(self, + request: Optional[Union[trip_api.CreateTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Creates a trip in the Fleet Engine and returns the + new trip. + + .. 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 fleetengine_v1 + + def sample_create_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateTripRequest( + parent="parent_value", + trip_id="trip_id_value", + ) + + # Make the request + response = client.create_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.CreateTripRequest, dict]): + The request object. CreateTrip 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.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.CreateTripRequest): + request = trip_api.CreateTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 get_trip(self, + request: Optional[Union[trip_api.GetTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Get information about a single trip. + + .. 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 fleetengine_v1 + + def sample_get_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetTripRequest( + name="name_value", + ) + + # Make the request + response = client.get_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.GetTripRequest, dict]): + The request object. GetTrip 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.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.GetTripRequest): + request = trip_api.GetTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 report_billable_trip(self, + request: Optional[Union[trip_api.ReportBillableTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Report billable trip usage. + + .. 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 fleetengine_v1 + + def sample_report_billable_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.ReportBillableTripRequest( + name="name_value", + country_code="country_code_value", + ) + + # Make the request + client.report_billable_trip(request=request) + + Args: + request (Union[google.maps.fleetengine_v1.types.ReportBillableTripRequest, dict]): + The request object. ReportBillableTrip 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. + """ + # 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, trip_api.ReportBillableTripRequest): + request = trip_api.ReportBillableTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.report_billable_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def search_trips(self, + request: Optional[Union[trip_api.SearchTripsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchTripsPager: + r"""Get all the trips for a specific vehicle. + + .. 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 fleetengine_v1 + + def sample_search_trips(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchTripsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.search_trips(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.SearchTripsRequest, dict]): + The request object. SearchTrips 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.fleetengine_v1.services.trip_service.pagers.SearchTripsPager: + SearchTrips response message. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # 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, trip_api.SearchTripsRequest): + request = trip_api.SearchTripsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_trips] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchTripsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_trip(self, + request: Optional[Union[trip_api.UpdateTripRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> trips.Trip: + r"""Updates trip data. + + .. 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 fleetengine_v1 + + def sample_update_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateTripRequest( + name="name_value", + ) + + # Make the request + response = client.update_trip(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.UpdateTripRequest, dict]): + The request object. UpdateTrip 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.fleetengine_v1.types.Trip: + Trip metadata. + """ + # 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, trip_api.UpdateTripRequest): + request = trip_api.UpdateTripRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_trip] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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) -> "TripServiceClient": + 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__ = ( + "TripServiceClient", +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py new file mode 100644 index 000000000000..8b5599f99cfa --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py @@ -0,0 +1,163 @@ +# -*- 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.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.maps.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips + + +class SearchTripsPager: + """A pager for iterating through ``search_trips`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``trips`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchTrips`` requests and continue to iterate + through the ``trips`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., trip_api.SearchTripsResponse], + request: trip_api.SearchTripsRequest, + response: trip_api.SearchTripsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_v1.types.SearchTripsRequest): + The initial request object. + response (google.maps.fleetengine_v1.types.SearchTripsResponse): + The initial response object. + 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. + """ + self._method = method + self._request = trip_api.SearchTripsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[trip_api.SearchTripsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[trips.Trip]: + for page in self.pages: + yield from page.trips + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchTripsAsyncPager: + """A pager for iterating through ``search_trips`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``trips`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchTrips`` requests and continue to iterate + through the ``trips`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[trip_api.SearchTripsResponse]], + request: trip_api.SearchTripsRequest, + response: trip_api.SearchTripsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_v1.types.SearchTripsRequest): + The initial request object. + response (google.maps.fleetengine_v1.types.SearchTripsResponse): + The initial response object. + retry (google.api_core.retry.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. + """ + self._method = method + self._request = trip_api.SearchTripsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[trip_api.SearchTripsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[trips.Trip]: + async def async_generator(): + async for page in self.pages: + for response in page.trips: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst new file mode 100644 index 000000000000..97675873407f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`TripServiceTransport` is the ABC for all transports. +- public child `TripServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `TripServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseTripServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `TripServiceRestTransport` 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-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py new file mode 100644 index 000000000000..89de6013d759 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- 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 TripServiceTransport +from .grpc import TripServiceGrpcTransport +from .grpc_asyncio import TripServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TripServiceTransport]] +_transport_registry['grpc'] = TripServiceGrpcTransport +_transport_registry['grpc_asyncio'] = TripServiceGrpcAsyncIOTransport + +__all__ = ( + 'TripServiceTransport', + 'TripServiceGrpcTransport', + 'TripServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py new file mode 100644 index 000000000000..71595601d903 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py @@ -0,0 +1,248 @@ +# -*- 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.fleetengine_v1 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.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class TripServiceTransport(abc.ABC): + """Abstract transport class for TripService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'fleetengine.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: 'fleetengine.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.create_trip: gapic_v1.method.wrap_method( + self.create_trip, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.get_trip: gapic_v1.method.wrap_method( + self.get_trip, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.report_billable_trip: gapic_v1.method.wrap_method( + self.report_billable_trip, + default_timeout=None, + client_info=client_info, + ), + self.search_trips: gapic_v1.method.wrap_method( + self.search_trips, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_trip: gapic_v1.method.wrap_method( + self.update_trip, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + 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 create_trip(self) -> Callable[ + [trip_api.CreateTripRequest], + Union[ + trips.Trip, + Awaitable[trips.Trip] + ]]: + raise NotImplementedError() + + @property + def get_trip(self) -> Callable[ + [trip_api.GetTripRequest], + Union[ + trips.Trip, + Awaitable[trips.Trip] + ]]: + raise NotImplementedError() + + @property + def report_billable_trip(self) -> Callable[ + [trip_api.ReportBillableTripRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def search_trips(self) -> Callable[ + [trip_api.SearchTripsRequest], + Union[ + trip_api.SearchTripsResponse, + Awaitable[trip_api.SearchTripsResponse] + ]]: + raise NotImplementedError() + + @property + def update_trip(self) -> Callable[ + [trip_api.UpdateTripRequest], + Union[ + trips.Trip, + Awaitable[trips.Trip] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'TripServiceTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py new file mode 100644 index 000000000000..0c20dd7934fc --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py @@ -0,0 +1,377 @@ +# -*- 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.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +from google.protobuf import empty_pb2 # type: ignore +from .base import TripServiceTransport, DEFAULT_CLIENT_INFO + + +class TripServiceGrpcTransport(TripServiceTransport): + """gRPC backend transport for TripService. + + Trip management service. + + 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 = 'fleetengine.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: 'fleetengine.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 = 'fleetengine.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 create_trip(self) -> Callable[ + [trip_api.CreateTripRequest], + trips.Trip]: + r"""Return a callable for the create trip method over gRPC. + + Creates a trip in the Fleet Engine and returns the + new trip. + + Returns: + Callable[[~.CreateTripRequest], + ~.Trip]: + 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 'create_trip' not in self._stubs: + self._stubs['create_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/CreateTrip', + request_serializer=trip_api.CreateTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['create_trip'] + + @property + def get_trip(self) -> Callable[ + [trip_api.GetTripRequest], + trips.Trip]: + r"""Return a callable for the get trip method over gRPC. + + Get information about a single trip. + + Returns: + Callable[[~.GetTripRequest], + ~.Trip]: + 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 'get_trip' not in self._stubs: + self._stubs['get_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/GetTrip', + request_serializer=trip_api.GetTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['get_trip'] + + @property + def report_billable_trip(self) -> Callable[ + [trip_api.ReportBillableTripRequest], + empty_pb2.Empty]: + r"""Return a callable for the report billable trip method over gRPC. + + Report billable trip usage. + + Returns: + Callable[[~.ReportBillableTripRequest], + ~.Empty]: + 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 'report_billable_trip' not in self._stubs: + self._stubs['report_billable_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/ReportBillableTrip', + request_serializer=trip_api.ReportBillableTripRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['report_billable_trip'] + + @property + def search_trips(self) -> Callable[ + [trip_api.SearchTripsRequest], + trip_api.SearchTripsResponse]: + r"""Return a callable for the search trips method over gRPC. + + Get all the trips for a specific vehicle. + + Returns: + Callable[[~.SearchTripsRequest], + ~.SearchTripsResponse]: + 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 'search_trips' not in self._stubs: + self._stubs['search_trips'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/SearchTrips', + request_serializer=trip_api.SearchTripsRequest.serialize, + response_deserializer=trip_api.SearchTripsResponse.deserialize, + ) + return self._stubs['search_trips'] + + @property + def update_trip(self) -> Callable[ + [trip_api.UpdateTripRequest], + trips.Trip]: + r"""Return a callable for the update trip method over gRPC. + + Updates trip data. + + Returns: + Callable[[~.UpdateTripRequest], + ~.Trip]: + 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 'update_trip' not in self._stubs: + self._stubs['update_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/UpdateTrip', + request_serializer=trip_api.UpdateTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['update_trip'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'TripServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..b7b838015e6d --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py @@ -0,0 +1,454 @@ +# -*- 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.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +from google.protobuf import empty_pb2 # type: ignore +from .base import TripServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import TripServiceGrpcTransport + + +class TripServiceGrpcAsyncIOTransport(TripServiceTransport): + """gRPC AsyncIO backend transport for TripService. + + Trip management service. + + 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 = 'fleetengine.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 = 'fleetengine.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: 'fleetengine.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 create_trip(self) -> Callable[ + [trip_api.CreateTripRequest], + Awaitable[trips.Trip]]: + r"""Return a callable for the create trip method over gRPC. + + Creates a trip in the Fleet Engine and returns the + new trip. + + Returns: + Callable[[~.CreateTripRequest], + Awaitable[~.Trip]]: + 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 'create_trip' not in self._stubs: + self._stubs['create_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/CreateTrip', + request_serializer=trip_api.CreateTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['create_trip'] + + @property + def get_trip(self) -> Callable[ + [trip_api.GetTripRequest], + Awaitable[trips.Trip]]: + r"""Return a callable for the get trip method over gRPC. + + Get information about a single trip. + + Returns: + Callable[[~.GetTripRequest], + Awaitable[~.Trip]]: + 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 'get_trip' not in self._stubs: + self._stubs['get_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/GetTrip', + request_serializer=trip_api.GetTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['get_trip'] + + @property + def report_billable_trip(self) -> Callable[ + [trip_api.ReportBillableTripRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the report billable trip method over gRPC. + + Report billable trip usage. + + Returns: + Callable[[~.ReportBillableTripRequest], + Awaitable[~.Empty]]: + 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 'report_billable_trip' not in self._stubs: + self._stubs['report_billable_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/ReportBillableTrip', + request_serializer=trip_api.ReportBillableTripRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['report_billable_trip'] + + @property + def search_trips(self) -> Callable[ + [trip_api.SearchTripsRequest], + Awaitable[trip_api.SearchTripsResponse]]: + r"""Return a callable for the search trips method over gRPC. + + Get all the trips for a specific vehicle. + + Returns: + Callable[[~.SearchTripsRequest], + Awaitable[~.SearchTripsResponse]]: + 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 'search_trips' not in self._stubs: + self._stubs['search_trips'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/SearchTrips', + request_serializer=trip_api.SearchTripsRequest.serialize, + response_deserializer=trip_api.SearchTripsResponse.deserialize, + ) + return self._stubs['search_trips'] + + @property + def update_trip(self) -> Callable[ + [trip_api.UpdateTripRequest], + Awaitable[trips.Trip]]: + r"""Return a callable for the update trip method over gRPC. + + Updates trip data. + + Returns: + Callable[[~.UpdateTripRequest], + Awaitable[~.Trip]]: + 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 'update_trip' not in self._stubs: + self._stubs['update_trip'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.TripService/UpdateTrip', + request_serializer=trip_api.UpdateTripRequest.serialize, + response_deserializer=trips.Trip.deserialize, + ) + return self._stubs['update_trip'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_trip: self._wrap_method( + self.create_trip, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.get_trip: self._wrap_method( + self.get_trip, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.report_billable_trip: self._wrap_method( + self.report_billable_trip, + default_timeout=None, + client_info=client_info, + ), + self.search_trips: self._wrap_method( + self.search_trips, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_trip: self._wrap_method( + self.update_trip, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + 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__ = ( + 'TripServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py new file mode 100644 index 000000000000..fc6cb2c02da7 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__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 VehicleServiceClient +from .async_client import VehicleServiceAsyncClient + +__all__ = ( + 'VehicleServiceClient', + 'VehicleServiceAsyncClient', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py new file mode 100644 index 000000000000..f5dcf834487a --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py @@ -0,0 +1,827 @@ +# -*- 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, Sequence, Tuple, Type, Union + +from google.maps.fleetengine_v1 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.fleetengine_v1.services.vehicle_service import pagers +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import VehicleServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import VehicleServiceGrpcAsyncIOTransport +from .client import VehicleServiceClient + + +class VehicleServiceAsyncClient: + """Vehicle management service.""" + + _client: VehicleServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = VehicleServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VehicleServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = VehicleServiceClient._DEFAULT_UNIVERSE + + vehicle_path = staticmethod(VehicleServiceClient.vehicle_path) + parse_vehicle_path = staticmethod(VehicleServiceClient.parse_vehicle_path) + common_billing_account_path = staticmethod(VehicleServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(VehicleServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(VehicleServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(VehicleServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(VehicleServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(VehicleServiceClient.parse_common_organization_path) + common_project_path = staticmethod(VehicleServiceClient.common_project_path) + parse_common_project_path = staticmethod(VehicleServiceClient.parse_common_project_path) + common_location_path = staticmethod(VehicleServiceClient.common_location_path) + parse_common_location_path = staticmethod(VehicleServiceClient.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: + VehicleServiceAsyncClient: The constructed client. + """ + return VehicleServiceClient.from_service_account_info.__func__(VehicleServiceAsyncClient, 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: + VehicleServiceAsyncClient: The constructed client. + """ + return VehicleServiceClient.from_service_account_file.__func__(VehicleServiceAsyncClient, 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 VehicleServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> VehicleServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VehicleServiceTransport: 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 = VehicleServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, VehicleServiceTransport, Callable[..., VehicleServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the vehicle service 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,VehicleServiceTransport,Callable[..., VehicleServiceTransport]]]): + 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 VehicleServiceTransport 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 = VehicleServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_vehicle(self, + request: Optional[Union[vehicle_api.CreateVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Instantiates a new vehicle associated with an on-demand + rideshare or deliveries provider. Each ``Vehicle`` must have a + unique vehicle ID. + + The following ``Vehicle`` fields are required when creating a + ``Vehicle``: + + - ``vehicleState`` + - ``supportedTripTypes`` + - ``maximumCapacity`` + - ``vehicleType`` + + The following ``Vehicle`` fields are ignored when creating a + ``Vehicle``: + + - ``name`` + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_version`` + - ``current_route_segment_traffic`` + - ``route`` + - ``waypoints`` + - ``waypoints_version`` + - ``remaining_distance_meters`` + - ``remaining_time_seconds`` + - ``eta_to_next_waypoint`` + - ``navigation_status`` + + All other fields are optional and used if provided. + + .. 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 fleetengine_v1 + + async def sample_create_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateVehicleRequest( + parent="parent_value", + vehicle_id="vehicle_id_value", + ) + + # Make the request + response = await client.create_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.CreateVehicleRequest, dict]]): + The request object. ``CreateVehicle`` 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.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.CreateVehicleRequest): + request = vehicle_api.CreateVehicleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 + + async def get_vehicle(self, + request: Optional[Union[vehicle_api.GetVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Returns a vehicle from the Fleet Engine. + + .. 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 fleetengine_v1 + + async def sample_get_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetVehicleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.GetVehicleRequest, dict]]): + The request object. ``GetVehicle`` 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.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.GetVehicleRequest): + request = vehicle_api.GetVehicleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 + + async def update_vehicle(self, + request: Optional[Union[vehicle_api.UpdateVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Writes updated vehicle data to the Fleet Engine. + + When updating a ``Vehicle``, the following fields cannot be + updated since they are managed by the server: + + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment_version`` + - ``waypoints_version`` + + The vehicle ``name`` also cannot be updated. + + If the ``attributes`` field is updated, **all** the vehicle's + attributes are replaced with the attributes provided in the + request. If you want to update only some attributes, see the + ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` + field can be updated, but must contain all the waypoints + currently on the vehicle, and no other waypoints. + + .. 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 fleetengine_v1 + + async def sample_update_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateVehicleRequest( + name="name_value", + ) + + # Make the request + response = await client.update_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.UpdateVehicleRequest, dict]]): + The request object. \`UpdateVehicle 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.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.UpdateVehicleRequest): + request = vehicle_api.UpdateVehicleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 + + async def update_vehicle_attributes(self, + request: Optional[Union[vehicle_api.UpdateVehicleAttributesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicle_api.UpdateVehicleAttributesResponse: + r"""Partially updates a vehicle's attributes. Only the attributes + mentioned in the request will be updated, other attributes will + NOT be altered. Note: this is different in ``UpdateVehicle``, + where the whole ``attributes`` field will be replaced by the one + in ``UpdateVehicleRequest``, attributes not in the request would + be removed. + + .. 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 fleetengine_v1 + + async def sample_update_vehicle_attributes(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + attributes = fleetengine_v1.VehicleAttribute() + attributes.string_value = "string_value_value" + + request = fleetengine_v1.UpdateVehicleAttributesRequest( + name="name_value", + attributes=attributes, + ) + + # Make the request + response = await client.update_vehicle_attributes(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest, dict]]): + The request object. ``UpdateVehicleAttributes`` 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.fleetengine_v1.types.UpdateVehicleAttributesResponse: + UpdateVehicleAttributes 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, vehicle_api.UpdateVehicleAttributesRequest): + request = vehicle_api.UpdateVehicleAttributesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_vehicle_attributes] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 + + async def list_vehicles(self, + request: Optional[Union[vehicle_api.ListVehiclesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVehiclesAsyncPager: + r"""Returns a paginated list of vehicles associated with + a provider that match the request options. + + .. 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 fleetengine_v1 + + async def sample_list_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.ListVehiclesRequest( + parent="parent_value", + vehicle_type_categories=['PEDESTRIAN'], + ) + + # Make the request + page_result = client.list_vehicles(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.ListVehiclesRequest, dict]]): + The request object. ``ListVehicles`` 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.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesAsyncPager: + ListVehicles response message. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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, vehicle_api.ListVehiclesRequest): + request = vehicle_api.ListVehiclesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_vehicles] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListVehiclesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_vehicles(self, + request: Optional[Union[vehicle_api.SearchVehiclesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicle_api.SearchVehiclesResponse: + r"""Returns a list of vehicles that match the request + options. + + .. 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 fleetengine_v1 + + async def sample_search_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchVehiclesRequest( + parent="parent_value", + pickup_radius_meters=2146, + count=553, + minimum_capacity=1705, + trip_types=['EXCLUSIVE'], + order_by="COST", + ) + + # Make the request + response = await client.search_vehicles(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.fleetengine_v1.types.SearchVehiclesRequest, dict]]): + The request object. ``SearchVehicles`` 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.fleetengine_v1.types.SearchVehiclesResponse: + SearchVehicles 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, vehicle_api.SearchVehiclesRequest): + request = vehicle_api.SearchVehiclesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.search_vehicles] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 + + async def __aenter__(self) -> "VehicleServiceAsyncClient": + 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__ = ( + "VehicleServiceAsyncClient", +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py new file mode 100644 index 000000000000..e88fa624c2d6 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py @@ -0,0 +1,1155 @@ +# -*- 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, Sequence, Tuple, Type, Union, cast +import warnings + +from google.maps.fleetengine_v1 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.fleetengine_v1.services.vehicle_service import pagers +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import VehicleServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import VehicleServiceGrpcTransport +from .transports.grpc_asyncio import VehicleServiceGrpcAsyncIOTransport + + +class VehicleServiceClientMeta(type): + """Metaclass for the VehicleService 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[VehicleServiceTransport]] + _transport_registry["grpc"] = VehicleServiceGrpcTransport + _transport_registry["grpc_asyncio"] = VehicleServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[VehicleServiceTransport]: + """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 VehicleServiceClient(metaclass=VehicleServiceClientMeta): + """Vehicle management service.""" + + @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 = "fleetengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "fleetengine.{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: + VehicleServiceClient: 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: + VehicleServiceClient: 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) -> VehicleServiceTransport: + """Returns the transport used by the client instance. + + Returns: + VehicleServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def vehicle_path(provider: str,vehicle: str,) -> str: + """Returns a fully-qualified vehicle string.""" + return "providers/{provider}/vehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) + + @staticmethod + def parse_vehicle_path(path: str) -> Dict[str,str]: + """Parses a vehicle path into its component segments.""" + m = re.match(r"^providers/(?P.+?)/vehicles/(?P.+?)$", path) + return m.groupdict() if m else {} + + @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 = VehicleServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = VehicleServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = VehicleServiceClient._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 = VehicleServiceClient._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, VehicleServiceTransport, Callable[..., VehicleServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the vehicle service 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,VehicleServiceTransport,Callable[..., VehicleServiceTransport]]]): + 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 VehicleServiceTransport 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 = VehicleServiceClient._read_environment_variables() + self._client_cert_source = VehicleServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = VehicleServiceClient._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, VehicleServiceTransport) + if transport_provided: + # transport is a VehicleServiceTransport 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(VehicleServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + VehicleServiceClient._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[VehicleServiceTransport], Callable[..., VehicleServiceTransport]] = ( + VehicleServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., VehicleServiceTransport], 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 create_vehicle(self, + request: Optional[Union[vehicle_api.CreateVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Instantiates a new vehicle associated with an on-demand + rideshare or deliveries provider. Each ``Vehicle`` must have a + unique vehicle ID. + + The following ``Vehicle`` fields are required when creating a + ``Vehicle``: + + - ``vehicleState`` + - ``supportedTripTypes`` + - ``maximumCapacity`` + - ``vehicleType`` + + The following ``Vehicle`` fields are ignored when creating a + ``Vehicle``: + + - ``name`` + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_version`` + - ``current_route_segment_traffic`` + - ``route`` + - ``waypoints`` + - ``waypoints_version`` + - ``remaining_distance_meters`` + - ``remaining_time_seconds`` + - ``eta_to_next_waypoint`` + - ``navigation_status`` + + All other fields are optional and used if provided. + + .. 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 fleetengine_v1 + + def sample_create_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateVehicleRequest( + parent="parent_value", + vehicle_id="vehicle_id_value", + ) + + # Make the request + response = client.create_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.CreateVehicleRequest, dict]): + The request object. ``CreateVehicle`` 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.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.CreateVehicleRequest): + request = vehicle_api.CreateVehicleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 get_vehicle(self, + request: Optional[Union[vehicle_api.GetVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Returns a vehicle from the Fleet Engine. + + .. 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 fleetengine_v1 + + def sample_get_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetVehicleRequest( + name="name_value", + ) + + # Make the request + response = client.get_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.GetVehicleRequest, dict]): + The request object. ``GetVehicle`` 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.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.GetVehicleRequest): + request = vehicle_api.GetVehicleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 update_vehicle(self, + request: Optional[Union[vehicle_api.UpdateVehicleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicles.Vehicle: + r"""Writes updated vehicle data to the Fleet Engine. + + When updating a ``Vehicle``, the following fields cannot be + updated since they are managed by the server: + + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment_version`` + - ``waypoints_version`` + + The vehicle ``name`` also cannot be updated. + + If the ``attributes`` field is updated, **all** the vehicle's + attributes are replaced with the attributes provided in the + request. If you want to update only some attributes, see the + ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` + field can be updated, but must contain all the waypoints + currently on the vehicle, and no other waypoints. + + .. 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 fleetengine_v1 + + def sample_update_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateVehicleRequest( + name="name_value", + ) + + # Make the request + response = client.update_vehicle(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.UpdateVehicleRequest, dict]): + The request object. \`UpdateVehicle 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.fleetengine_v1.types.Vehicle: + Vehicle metadata. + """ + # 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, vehicle_api.UpdateVehicleRequest): + request = vehicle_api.UpdateVehicleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_vehicle] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 update_vehicle_attributes(self, + request: Optional[Union[vehicle_api.UpdateVehicleAttributesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicle_api.UpdateVehicleAttributesResponse: + r"""Partially updates a vehicle's attributes. Only the attributes + mentioned in the request will be updated, other attributes will + NOT be altered. Note: this is different in ``UpdateVehicle``, + where the whole ``attributes`` field will be replaced by the one + in ``UpdateVehicleRequest``, attributes not in the request would + be removed. + + .. 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 fleetengine_v1 + + def sample_update_vehicle_attributes(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + attributes = fleetengine_v1.VehicleAttribute() + attributes.string_value = "string_value_value" + + request = fleetengine_v1.UpdateVehicleAttributesRequest( + name="name_value", + attributes=attributes, + ) + + # Make the request + response = client.update_vehicle_attributes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest, dict]): + The request object. ``UpdateVehicleAttributes`` 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.fleetengine_v1.types.UpdateVehicleAttributesResponse: + UpdateVehicleAttributes 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, vehicle_api.UpdateVehicleAttributesRequest): + request = vehicle_api.UpdateVehicleAttributesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_vehicle_attributes] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 list_vehicles(self, + request: Optional[Union[vehicle_api.ListVehiclesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVehiclesPager: + r"""Returns a paginated list of vehicles associated with + a provider that match the request options. + + .. 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 fleetengine_v1 + + def sample_list_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.ListVehiclesRequest( + parent="parent_value", + vehicle_type_categories=['PEDESTRIAN'], + ) + + # Make the request + page_result = client.list_vehicles(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.ListVehiclesRequest, dict]): + The request object. ``ListVehicles`` 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.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesPager: + ListVehicles response message. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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, vehicle_api.ListVehiclesRequest): + request = vehicle_api.ListVehiclesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_vehicles] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListVehiclesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_vehicles(self, + request: Optional[Union[vehicle_api.SearchVehiclesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vehicle_api.SearchVehiclesResponse: + r"""Returns a list of vehicles that match the request + options. + + .. 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 fleetengine_v1 + + def sample_search_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchVehiclesRequest( + parent="parent_value", + pickup_radius_meters=2146, + count=553, + minimum_capacity=1705, + trip_types=['EXCLUSIVE'], + order_by="COST", + ) + + # Make the request + response = client.search_vehicles(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.fleetengine_v1.types.SearchVehiclesRequest, dict]): + The request object. ``SearchVehicles`` 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.fleetengine_v1.types.SearchVehiclesResponse: + SearchVehicles 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, vehicle_api.SearchVehiclesRequest): + request = vehicle_api.SearchVehiclesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_vehicles] + + header_params = {} + + routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("provider_id"): + header_params["provider_id"] = regex_match.group("provider_id") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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) -> "VehicleServiceClient": + 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__ = ( + "VehicleServiceClient", +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py new file mode 100644 index 000000000000..a37cce62d28f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py @@ -0,0 +1,163 @@ +# -*- 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.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.maps.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles + + +class ListVehiclesPager: + """A pager for iterating through ``list_vehicles`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``vehicles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVehicles`` requests and continue to iterate + through the ``vehicles`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., vehicle_api.ListVehiclesResponse], + request: vehicle_api.ListVehiclesRequest, + response: vehicle_api.ListVehiclesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_v1.types.ListVehiclesRequest): + The initial request object. + response (google.maps.fleetengine_v1.types.ListVehiclesResponse): + The initial response object. + 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. + """ + self._method = method + self._request = vehicle_api.ListVehiclesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[vehicle_api.ListVehiclesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[vehicles.Vehicle]: + for page in self.pages: + yield from page.vehicles + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListVehiclesAsyncPager: + """A pager for iterating through ``list_vehicles`` requests. + + This class thinly wraps an initial + :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``vehicles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVehicles`` requests and continue to iterate + through the ``vehicles`` field on the + corresponding responses. + + All the usual :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[vehicle_api.ListVehiclesResponse]], + request: vehicle_api.ListVehiclesRequest, + response: vehicle_api.ListVehiclesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.maps.fleetengine_v1.types.ListVehiclesRequest): + The initial request object. + response (google.maps.fleetengine_v1.types.ListVehiclesResponse): + The initial response object. + retry (google.api_core.retry.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. + """ + self._method = method + self._request = vehicle_api.ListVehiclesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[vehicle_api.ListVehiclesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[vehicles.Vehicle]: + async def async_generator(): + async for page in self.pages: + for response in page.vehicles: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst new file mode 100644 index 000000000000..cab31a918dfd --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`VehicleServiceTransport` is the ABC for all transports. +- public child `VehicleServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `VehicleServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseVehicleServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `VehicleServiceRestTransport` 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-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py new file mode 100644 index 000000000000..6c5e9251815c --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- 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 VehicleServiceTransport +from .grpc import VehicleServiceGrpcTransport +from .grpc_asyncio import VehicleServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VehicleServiceTransport]] +_transport_registry['grpc'] = VehicleServiceGrpcTransport +_transport_registry['grpc_asyncio'] = VehicleServiceGrpcAsyncIOTransport + +__all__ = ( + 'VehicleServiceTransport', + 'VehicleServiceGrpcTransport', + 'VehicleServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py new file mode 100644 index 000000000000..7f3a046bb15d --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py @@ -0,0 +1,270 @@ +# -*- 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.fleetengine_v1 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.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class VehicleServiceTransport(abc.ABC): + """Abstract transport class for VehicleService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'fleetengine.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: 'fleetengine.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.create_vehicle: gapic_v1.method.wrap_method( + self.create_vehicle, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.get_vehicle: gapic_v1.method.wrap_method( + self.get_vehicle, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_vehicle: gapic_v1.method.wrap_method( + self.update_vehicle, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_vehicle_attributes: gapic_v1.method.wrap_method( + self.update_vehicle_attributes, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.list_vehicles: gapic_v1.method.wrap_method( + self.list_vehicles, + default_timeout=None, + client_info=client_info, + ), + self.search_vehicles: gapic_v1.method.wrap_method( + self.search_vehicles, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + 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 create_vehicle(self) -> Callable[ + [vehicle_api.CreateVehicleRequest], + Union[ + vehicles.Vehicle, + Awaitable[vehicles.Vehicle] + ]]: + raise NotImplementedError() + + @property + def get_vehicle(self) -> Callable[ + [vehicle_api.GetVehicleRequest], + Union[ + vehicles.Vehicle, + Awaitable[vehicles.Vehicle] + ]]: + raise NotImplementedError() + + @property + def update_vehicle(self) -> Callable[ + [vehicle_api.UpdateVehicleRequest], + Union[ + vehicles.Vehicle, + Awaitable[vehicles.Vehicle] + ]]: + raise NotImplementedError() + + @property + def update_vehicle_attributes(self) -> Callable[ + [vehicle_api.UpdateVehicleAttributesRequest], + Union[ + vehicle_api.UpdateVehicleAttributesResponse, + Awaitable[vehicle_api.UpdateVehicleAttributesResponse] + ]]: + raise NotImplementedError() + + @property + def list_vehicles(self) -> Callable[ + [vehicle_api.ListVehiclesRequest], + Union[ + vehicle_api.ListVehiclesResponse, + Awaitable[vehicle_api.ListVehiclesResponse] + ]]: + raise NotImplementedError() + + @property + def search_vehicles(self) -> Callable[ + [vehicle_api.SearchVehiclesRequest], + Union[ + vehicle_api.SearchVehiclesResponse, + Awaitable[vehicle_api.SearchVehiclesResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'VehicleServiceTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py new file mode 100644 index 000000000000..827cc20bd1dd --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py @@ -0,0 +1,455 @@ +# -*- 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.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles +from .base import VehicleServiceTransport, DEFAULT_CLIENT_INFO + + +class VehicleServiceGrpcTransport(VehicleServiceTransport): + """gRPC backend transport for VehicleService. + + Vehicle management service. + + 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 = 'fleetengine.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: 'fleetengine.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 = 'fleetengine.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 create_vehicle(self) -> Callable[ + [vehicle_api.CreateVehicleRequest], + vehicles.Vehicle]: + r"""Return a callable for the create vehicle method over gRPC. + + Instantiates a new vehicle associated with an on-demand + rideshare or deliveries provider. Each ``Vehicle`` must have a + unique vehicle ID. + + The following ``Vehicle`` fields are required when creating a + ``Vehicle``: + + - ``vehicleState`` + - ``supportedTripTypes`` + - ``maximumCapacity`` + - ``vehicleType`` + + The following ``Vehicle`` fields are ignored when creating a + ``Vehicle``: + + - ``name`` + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_version`` + - ``current_route_segment_traffic`` + - ``route`` + - ``waypoints`` + - ``waypoints_version`` + - ``remaining_distance_meters`` + - ``remaining_time_seconds`` + - ``eta_to_next_waypoint`` + - ``navigation_status`` + + All other fields are optional and used if provided. + + Returns: + Callable[[~.CreateVehicleRequest], + ~.Vehicle]: + 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 'create_vehicle' not in self._stubs: + self._stubs['create_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/CreateVehicle', + request_serializer=vehicle_api.CreateVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['create_vehicle'] + + @property + def get_vehicle(self) -> Callable[ + [vehicle_api.GetVehicleRequest], + vehicles.Vehicle]: + r"""Return a callable for the get vehicle method over gRPC. + + Returns a vehicle from the Fleet Engine. + + Returns: + Callable[[~.GetVehicleRequest], + ~.Vehicle]: + 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 'get_vehicle' not in self._stubs: + self._stubs['get_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/GetVehicle', + request_serializer=vehicle_api.GetVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['get_vehicle'] + + @property + def update_vehicle(self) -> Callable[ + [vehicle_api.UpdateVehicleRequest], + vehicles.Vehicle]: + r"""Return a callable for the update vehicle method over gRPC. + + Writes updated vehicle data to the Fleet Engine. + + When updating a ``Vehicle``, the following fields cannot be + updated since they are managed by the server: + + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment_version`` + - ``waypoints_version`` + + The vehicle ``name`` also cannot be updated. + + If the ``attributes`` field is updated, **all** the vehicle's + attributes are replaced with the attributes provided in the + request. If you want to update only some attributes, see the + ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` + field can be updated, but must contain all the waypoints + currently on the vehicle, and no other waypoints. + + Returns: + Callable[[~.UpdateVehicleRequest], + ~.Vehicle]: + 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 'update_vehicle' not in self._stubs: + self._stubs['update_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/UpdateVehicle', + request_serializer=vehicle_api.UpdateVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['update_vehicle'] + + @property + def update_vehicle_attributes(self) -> Callable[ + [vehicle_api.UpdateVehicleAttributesRequest], + vehicle_api.UpdateVehicleAttributesResponse]: + r"""Return a callable for the update vehicle attributes method over gRPC. + + Partially updates a vehicle's attributes. Only the attributes + mentioned in the request will be updated, other attributes will + NOT be altered. Note: this is different in ``UpdateVehicle``, + where the whole ``attributes`` field will be replaced by the one + in ``UpdateVehicleRequest``, attributes not in the request would + be removed. + + Returns: + Callable[[~.UpdateVehicleAttributesRequest], + ~.UpdateVehicleAttributesResponse]: + 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 'update_vehicle_attributes' not in self._stubs: + self._stubs['update_vehicle_attributes'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/UpdateVehicleAttributes', + request_serializer=vehicle_api.UpdateVehicleAttributesRequest.serialize, + response_deserializer=vehicle_api.UpdateVehicleAttributesResponse.deserialize, + ) + return self._stubs['update_vehicle_attributes'] + + @property + def list_vehicles(self) -> Callable[ + [vehicle_api.ListVehiclesRequest], + vehicle_api.ListVehiclesResponse]: + r"""Return a callable for the list vehicles method over gRPC. + + Returns a paginated list of vehicles associated with + a provider that match the request options. + + Returns: + Callable[[~.ListVehiclesRequest], + ~.ListVehiclesResponse]: + 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 'list_vehicles' not in self._stubs: + self._stubs['list_vehicles'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/ListVehicles', + request_serializer=vehicle_api.ListVehiclesRequest.serialize, + response_deserializer=vehicle_api.ListVehiclesResponse.deserialize, + ) + return self._stubs['list_vehicles'] + + @property + def search_vehicles(self) -> Callable[ + [vehicle_api.SearchVehiclesRequest], + vehicle_api.SearchVehiclesResponse]: + r"""Return a callable for the search vehicles method over gRPC. + + Returns a list of vehicles that match the request + options. + + Returns: + Callable[[~.SearchVehiclesRequest], + ~.SearchVehiclesResponse]: + 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 'search_vehicles' not in self._stubs: + self._stubs['search_vehicles'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/SearchVehicles', + request_serializer=vehicle_api.SearchVehiclesRequest.serialize, + response_deserializer=vehicle_api.SearchVehiclesResponse.deserialize, + ) + return self._stubs['search_vehicles'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'VehicleServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..952dd0c816f8 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py @@ -0,0 +1,546 @@ +# -*- 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.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles +from .base import VehicleServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import VehicleServiceGrpcTransport + + +class VehicleServiceGrpcAsyncIOTransport(VehicleServiceTransport): + """gRPC AsyncIO backend transport for VehicleService. + + Vehicle management service. + + 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 = 'fleetengine.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 = 'fleetengine.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: 'fleetengine.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 create_vehicle(self) -> Callable[ + [vehicle_api.CreateVehicleRequest], + Awaitable[vehicles.Vehicle]]: + r"""Return a callable for the create vehicle method over gRPC. + + Instantiates a new vehicle associated with an on-demand + rideshare or deliveries provider. Each ``Vehicle`` must have a + unique vehicle ID. + + The following ``Vehicle`` fields are required when creating a + ``Vehicle``: + + - ``vehicleState`` + - ``supportedTripTypes`` + - ``maximumCapacity`` + - ``vehicleType`` + + The following ``Vehicle`` fields are ignored when creating a + ``Vehicle``: + + - ``name`` + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_version`` + - ``current_route_segment_traffic`` + - ``route`` + - ``waypoints`` + - ``waypoints_version`` + - ``remaining_distance_meters`` + - ``remaining_time_seconds`` + - ``eta_to_next_waypoint`` + - ``navigation_status`` + + All other fields are optional and used if provided. + + Returns: + Callable[[~.CreateVehicleRequest], + Awaitable[~.Vehicle]]: + 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 'create_vehicle' not in self._stubs: + self._stubs['create_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/CreateVehicle', + request_serializer=vehicle_api.CreateVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['create_vehicle'] + + @property + def get_vehicle(self) -> Callable[ + [vehicle_api.GetVehicleRequest], + Awaitable[vehicles.Vehicle]]: + r"""Return a callable for the get vehicle method over gRPC. + + Returns a vehicle from the Fleet Engine. + + Returns: + Callable[[~.GetVehicleRequest], + Awaitable[~.Vehicle]]: + 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 'get_vehicle' not in self._stubs: + self._stubs['get_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/GetVehicle', + request_serializer=vehicle_api.GetVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['get_vehicle'] + + @property + def update_vehicle(self) -> Callable[ + [vehicle_api.UpdateVehicleRequest], + Awaitable[vehicles.Vehicle]]: + r"""Return a callable for the update vehicle method over gRPC. + + Writes updated vehicle data to the Fleet Engine. + + When updating a ``Vehicle``, the following fields cannot be + updated since they are managed by the server: + + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment_version`` + - ``waypoints_version`` + + The vehicle ``name`` also cannot be updated. + + If the ``attributes`` field is updated, **all** the vehicle's + attributes are replaced with the attributes provided in the + request. If you want to update only some attributes, see the + ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` + field can be updated, but must contain all the waypoints + currently on the vehicle, and no other waypoints. + + Returns: + Callable[[~.UpdateVehicleRequest], + Awaitable[~.Vehicle]]: + 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 'update_vehicle' not in self._stubs: + self._stubs['update_vehicle'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/UpdateVehicle', + request_serializer=vehicle_api.UpdateVehicleRequest.serialize, + response_deserializer=vehicles.Vehicle.deserialize, + ) + return self._stubs['update_vehicle'] + + @property + def update_vehicle_attributes(self) -> Callable[ + [vehicle_api.UpdateVehicleAttributesRequest], + Awaitable[vehicle_api.UpdateVehicleAttributesResponse]]: + r"""Return a callable for the update vehicle attributes method over gRPC. + + Partially updates a vehicle's attributes. Only the attributes + mentioned in the request will be updated, other attributes will + NOT be altered. Note: this is different in ``UpdateVehicle``, + where the whole ``attributes`` field will be replaced by the one + in ``UpdateVehicleRequest``, attributes not in the request would + be removed. + + Returns: + Callable[[~.UpdateVehicleAttributesRequest], + Awaitable[~.UpdateVehicleAttributesResponse]]: + 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 'update_vehicle_attributes' not in self._stubs: + self._stubs['update_vehicle_attributes'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/UpdateVehicleAttributes', + request_serializer=vehicle_api.UpdateVehicleAttributesRequest.serialize, + response_deserializer=vehicle_api.UpdateVehicleAttributesResponse.deserialize, + ) + return self._stubs['update_vehicle_attributes'] + + @property + def list_vehicles(self) -> Callable[ + [vehicle_api.ListVehiclesRequest], + Awaitable[vehicle_api.ListVehiclesResponse]]: + r"""Return a callable for the list vehicles method over gRPC. + + Returns a paginated list of vehicles associated with + a provider that match the request options. + + Returns: + Callable[[~.ListVehiclesRequest], + Awaitable[~.ListVehiclesResponse]]: + 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 'list_vehicles' not in self._stubs: + self._stubs['list_vehicles'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/ListVehicles', + request_serializer=vehicle_api.ListVehiclesRequest.serialize, + response_deserializer=vehicle_api.ListVehiclesResponse.deserialize, + ) + return self._stubs['list_vehicles'] + + @property + def search_vehicles(self) -> Callable[ + [vehicle_api.SearchVehiclesRequest], + Awaitable[vehicle_api.SearchVehiclesResponse]]: + r"""Return a callable for the search vehicles method over gRPC. + + Returns a list of vehicles that match the request + options. + + Returns: + Callable[[~.SearchVehiclesRequest], + Awaitable[~.SearchVehiclesResponse]]: + 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 'search_vehicles' not in self._stubs: + self._stubs['search_vehicles'] = self.grpc_channel.unary_unary( + '/maps.fleetengine.v1.VehicleService/SearchVehicles', + request_serializer=vehicle_api.SearchVehiclesRequest.serialize, + response_deserializer=vehicle_api.SearchVehiclesResponse.deserialize, + ) + return self._stubs['search_vehicles'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_vehicle: self._wrap_method( + self.create_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.get_vehicle: self._wrap_method( + self.get_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_vehicle: self._wrap_method( + self.update_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_vehicle_attributes: self._wrap_method( + self.update_vehicle_attributes, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.list_vehicles: self._wrap_method( + self.list_vehicles, + default_timeout=None, + client_info=client_info, + ), + self.search_vehicles: self._wrap_method( + self.search_vehicles, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + 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__ = ( + 'VehicleServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py new file mode 100644 index 000000000000..cba18024bd88 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py @@ -0,0 +1,124 @@ +# -*- 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 .fleetengine import ( + TerminalLocation, + TerminalPointId, + TripWaypoint, + VehicleAttribute, + VehicleLocation, + LocationSensor, + NavigationStatus, + PolylineFormatType, + TripType, + WaypointType, +) +from .header import ( + RequestHeader, +) +from .traffic import ( + ConsumableTrafficPolyline, + SpeedReadingInterval, +) +from .trip_api import ( + CreateTripRequest, + GetTripRequest, + ReportBillableTripRequest, + SearchTripsRequest, + SearchTripsResponse, + UpdateTripRequest, +) +from .trips import ( + StopLocation, + Trip, + BillingPlatformIdentifier, + TripStatus, + TripView, +) +from .vehicle_api import ( + CreateVehicleRequest, + GetVehicleRequest, + ListVehiclesRequest, + ListVehiclesResponse, + SearchVehiclesRequest, + SearchVehiclesResponse, + UpdateVehicleAttributesRequest, + UpdateVehicleAttributesResponse, + UpdateVehicleRequest, + VehicleAttributeList, + VehicleMatch, + Waypoint, +) +from .vehicles import ( + BatteryInfo, + DeviceSettings, + LicensePlate, + TrafficPolylineData, + Vehicle, + VisualTrafficReportPolylineRendering, + BatteryStatus, + LocationPowerSaveMode, + PowerSource, + VehicleState, +) + +__all__ = ( + 'TerminalLocation', + 'TerminalPointId', + 'TripWaypoint', + 'VehicleAttribute', + 'VehicleLocation', + 'LocationSensor', + 'NavigationStatus', + 'PolylineFormatType', + 'TripType', + 'WaypointType', + 'RequestHeader', + 'ConsumableTrafficPolyline', + 'SpeedReadingInterval', + 'CreateTripRequest', + 'GetTripRequest', + 'ReportBillableTripRequest', + 'SearchTripsRequest', + 'SearchTripsResponse', + 'UpdateTripRequest', + 'StopLocation', + 'Trip', + 'BillingPlatformIdentifier', + 'TripStatus', + 'TripView', + 'CreateVehicleRequest', + 'GetVehicleRequest', + 'ListVehiclesRequest', + 'ListVehiclesResponse', + 'SearchVehiclesRequest', + 'SearchVehiclesResponse', + 'UpdateVehicleAttributesRequest', + 'UpdateVehicleAttributesResponse', + 'UpdateVehicleRequest', + 'VehicleAttributeList', + 'VehicleMatch', + 'Waypoint', + 'BatteryInfo', + 'DeviceSettings', + 'LicensePlate', + 'TrafficPolylineData', + 'Vehicle', + 'VisualTrafficReportPolylineRendering', + 'BatteryStatus', + 'LocationPowerSaveMode', + 'PowerSource', + 'VehicleState', +) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py new file mode 100644 index 000000000000..95fe3f592984 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py @@ -0,0 +1,628 @@ +# -*- 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.fleetengine_v1.types import traffic +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.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'TripType', + 'WaypointType', + 'PolylineFormatType', + 'NavigationStatus', + 'LocationSensor', + 'TerminalPointId', + 'TerminalLocation', + 'TripWaypoint', + 'VehicleAttribute', + 'VehicleLocation', + }, +) + + +class TripType(proto.Enum): + r"""The type of a trip. + + Values: + UNKNOWN_TRIP_TYPE (0): + Default, used for unspecified or unrecognized + trip types. + SHARED (1): + The trip may share a vehicle with other + trips. + EXCLUSIVE (2): + The trip is exclusive to a vehicle. + """ + UNKNOWN_TRIP_TYPE = 0 + SHARED = 1 + EXCLUSIVE = 2 + + +class WaypointType(proto.Enum): + r"""The type of waypoint. + + Values: + UNKNOWN_WAYPOINT_TYPE (0): + Unknown or unspecified waypoint type. + PICKUP_WAYPOINT_TYPE (1): + Waypoints for picking up riders or items. + DROP_OFF_WAYPOINT_TYPE (2): + Waypoints for dropping off riders or items. + INTERMEDIATE_DESTINATION_WAYPOINT_TYPE (3): + Waypoints for intermediate destinations in a + multi-destination trip. + """ + UNKNOWN_WAYPOINT_TYPE = 0 + PICKUP_WAYPOINT_TYPE = 1 + DROP_OFF_WAYPOINT_TYPE = 2 + INTERMEDIATE_DESTINATION_WAYPOINT_TYPE = 3 + + +class PolylineFormatType(proto.Enum): + r"""The type of polyline format. + + Values: + UNKNOWN_FORMAT_TYPE (0): + The format is unspecified or unknown. + LAT_LNG_LIST_TYPE (1): + A list of ``google.type.LatLng``. + ENCODED_POLYLINE_TYPE (2): + A polyline encoded with a polyline + compression algorithm. Decoding is not yet + supported. + """ + UNKNOWN_FORMAT_TYPE = 0 + LAT_LNG_LIST_TYPE = 1 + ENCODED_POLYLINE_TYPE = 2 + + +class NavigationStatus(proto.Enum): + r"""The vehicle's navigation status. + + Values: + UNKNOWN_NAVIGATION_STATUS (0): + Unspecified navigation status. + NO_GUIDANCE (1): + The Driver app's navigation is in ``FREE_NAV`` mode. + ENROUTE_TO_DESTINATION (2): + Turn-by-turn navigation is available and the Driver app + navigation has entered ``GUIDED_NAV`` mode. + OFF_ROUTE (3): + The vehicle has gone off the suggested route. + ARRIVED_AT_DESTINATION (4): + The vehicle is within approximately 50m of + the destination. + """ + UNKNOWN_NAVIGATION_STATUS = 0 + NO_GUIDANCE = 1 + ENROUTE_TO_DESTINATION = 2 + OFF_ROUTE = 3 + ARRIVED_AT_DESTINATION = 4 + + +class LocationSensor(proto.Enum): + r"""The sensor or methodology used to determine the location. + + Values: + UNKNOWN_SENSOR (0): + The sensor is unspecified or unknown. + GPS (1): + GPS or Assisted GPS. + NETWORK (2): + Assisted GPS, cell tower ID, or WiFi access + point. + PASSIVE (3): + Cell tower ID or WiFi access point. + ROAD_SNAPPED_LOCATION_PROVIDER (4): + A location determined by the mobile device to + be the most likely road position. + CUSTOMER_SUPPLIED_LOCATION (5): + A customer-supplied location from an independent source. + Typically, this value is used for a location provided from + sources other than the mobile device running Driver SDK. If + the original source is described by one of the other enum + values, use that value. Locations marked + CUSTOMER_SUPPLIED_LOCATION are typically provided via a + Vehicle's ``last_location.supplemental_location_sensor``. + FLEET_ENGINE_LOCATION (6): + A location calculated by Fleet Engine based + on the signals available to it. Output only. + This value will be rejected if it is received in + a request. + FUSED_LOCATION_PROVIDER (100): + Android's Fused Location Provider. + CORE_LOCATION (200): + The location provider on Apple operating + systems. + """ + UNKNOWN_SENSOR = 0 + GPS = 1 + NETWORK = 2 + PASSIVE = 3 + ROAD_SNAPPED_LOCATION_PROVIDER = 4 + CUSTOMER_SUPPLIED_LOCATION = 5 + FLEET_ENGINE_LOCATION = 6 + FUSED_LOCATION_PROVIDER = 100 + CORE_LOCATION = 200 + + +class TerminalPointId(proto.Message): + r"""Deprecated: TerminalPoints are no longer supported in Fleet Engine. + Use ``TerminalLocation.point`` instead. + + 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: + place_id (str): + Deprecated. + + This field is a member of `oneof`_ ``Id``. + generated_id (str): + Deprecated. + + This field is a member of `oneof`_ ``Id``. + value (str): + Deprecated. + """ + + place_id: str = proto.Field( + proto.STRING, + number=2, + oneof='Id', + ) + generated_id: str = proto.Field( + proto.STRING, + number=3, + oneof='Id', + ) + value: str = proto.Field( + proto.STRING, + number=4, + ) + + +class TerminalLocation(proto.Message): + r"""Describes the location of a waypoint. + + Attributes: + point (google.type.latlng_pb2.LatLng): + Required. Denotes the location of a trip + waypoint. + terminal_point_id (google.maps.fleetengine_v1.types.TerminalPointId): + Deprecated: Specify the ``point`` field instead. + access_point_id (str): + Deprecated: Specify the ``point`` field instead. + trip_id (str): + Deprecated. + terminal_location_type (google.maps.fleetengine_v1.types.WaypointType): + Deprecated: ``Vehicle.waypoint`` will have this data. + """ + + point: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + terminal_point_id: 'TerminalPointId' = proto.Field( + proto.MESSAGE, + number=2, + message='TerminalPointId', + ) + access_point_id: str = proto.Field( + proto.STRING, + number=3, + ) + trip_id: str = proto.Field( + proto.STRING, + number=4, + ) + terminal_location_type: 'WaypointType' = proto.Field( + proto.ENUM, + number=5, + enum='WaypointType', + ) + + +class TripWaypoint(proto.Message): + r"""Describes a stopping point on a vehicle's route or an ending + point on a vehicle's trip. + + Attributes: + location (google.maps.fleetengine_v1.types.TerminalLocation): + The location of this waypoint. + trip_id (str): + The trip associated with this waypoint. + waypoint_type (google.maps.fleetengine_v1.types.WaypointType): + The role this waypoint plays in this trip, + such as pickup or dropoff. + path_to_waypoint (MutableSequence[google.type.latlng_pb2.LatLng]): + The path from the previous waypoint to the + current waypoint. Undefined for the first + waypoint in a list. This field is only populated + when requested. + encoded_path_to_waypoint (str): + The encoded path from the previous waypoint + to the current waypoint. +

Note: This field is intended only for use by + the Driver SDK and Consumer SDK. Decoding is not + yet supported. + traffic_to_waypoint (google.maps.fleetengine_v1.types.ConsumableTrafficPolyline): + The traffic conditions along the path to this + waypoint. Note that traffic is only available + for Google Map Platform Rides and Deliveries + Solution customers. + distance_meters (google.protobuf.wrappers_pb2.Int32Value): + The path distance from the previous waypoint + to the current waypoint. Undefined for the first + waypoint in a list. + eta (google.protobuf.timestamp_pb2.Timestamp): + The estimated time of arrival at this + waypoint. Undefined for the first waypoint in a + list. + duration (google.protobuf.duration_pb2.Duration): + The travel time from previous waypoint to + this point. Undefined for the first waypoint in + a list. + """ + + location: 'TerminalLocation' = proto.Field( + proto.MESSAGE, + number=1, + message='TerminalLocation', + ) + trip_id: str = proto.Field( + proto.STRING, + number=2, + ) + waypoint_type: 'WaypointType' = proto.Field( + proto.ENUM, + number=3, + enum='WaypointType', + ) + path_to_waypoint: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=latlng_pb2.LatLng, + ) + encoded_path_to_waypoint: str = proto.Field( + proto.STRING, + number=5, + ) + traffic_to_waypoint: traffic.ConsumableTrafficPolyline = proto.Field( + proto.MESSAGE, + number=10, + message=traffic.ConsumableTrafficPolyline, + ) + distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.Int32Value, + ) + eta: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class VehicleAttribute(proto.Message): + r"""Describes a vehicle attribute as a key-value pair. The + "key:value" string length cannot exceed 256 characters. + + 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: + key (str): + The attribute's key. Keys may not contain the + colon character (:). + value (str): + The attribute's value. + string_value (str): + String typed attribute value. + + Note: This is identical to the ``value`` field which will + eventually be deprecated. For create or update methods, + either field can be used, but it's strongly recommended to + use ``string_value``. If both ``string_value`` and ``value`` + are set, they must be identical or an error will be thrown. + Both fields are populated in responses. + + This field is a member of `oneof`_ ``vehicle_attribute_value``. + bool_value (bool): + Boolean typed attribute value. + + This field is a member of `oneof`_ ``vehicle_attribute_value``. + number_value (float): + Double typed attribute value. + + This field is a member of `oneof`_ ``vehicle_attribute_value``. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + string_value: str = proto.Field( + proto.STRING, + number=3, + oneof='vehicle_attribute_value', + ) + bool_value: bool = proto.Field( + proto.BOOL, + number=4, + oneof='vehicle_attribute_value', + ) + number_value: float = proto.Field( + proto.DOUBLE, + number=5, + oneof='vehicle_attribute_value', + ) + + +class VehicleLocation(proto.Message): + r"""The location, speed, and heading of a vehicle at a point in + time. + + Attributes: + location (google.type.latlng_pb2.LatLng): + The location of the vehicle. When it is sent to Fleet + Engine, the vehicle's location is a GPS location. When you + receive it in a response, the vehicle's location can be + either a GPS location, a supplemental location, or some + other estimated location. The source is specified in + ``location_sensor``. + horizontal_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Deprecated: Use ``latlng_accuracy`` instead. + latlng_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``location`` in meters as a radius. + heading (google.protobuf.wrappers_pb2.Int32Value): + Direction the vehicle is moving in degrees. 0 represents + North. The valid range is [0,360). + bearing_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Deprecated: Use ``heading_accuracy`` instead. + heading_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``heading`` in degrees. + altitude (google.protobuf.wrappers_pb2.DoubleValue): + Altitude in meters above WGS84. + vertical_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Deprecated: Use ``altitude_accuracy`` instead. + altitude_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``altitude`` in meters. + speed_kmph (google.protobuf.wrappers_pb2.Int32Value): + Speed of the vehicle in kilometers per hour. Deprecated: Use + ``speed`` instead. + speed (google.protobuf.wrappers_pb2.DoubleValue): + Speed of the vehicle in meters/second + speed_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``speed`` in meters/second. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when ``location`` was reported by the sensor + according to the sensor's clock. + server_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the server + received the location information. + location_sensor (google.maps.fleetengine_v1.types.LocationSensor): + Provider of location data (for example, ``GPS``). + is_road_snapped (google.protobuf.wrappers_pb2.BoolValue): + Whether ``location`` is snapped to a road. + is_gps_sensor_enabled (google.protobuf.wrappers_pb2.BoolValue): + Input only. Indicates whether the GPS sensor + is enabled on the mobile device. + time_since_update (google.protobuf.wrappers_pb2.Int32Value): + Input only. Time (in seconds) since this + location was first sent to the server. This will + be zero for the first update. If the time is + unknown (for example, when the app restarts), + this value resets to zero. + num_stale_updates (google.protobuf.wrappers_pb2.Int32Value): + Input only. Deprecated: Other signals are now + used to determine if a location is stale. + raw_location (google.type.latlng_pb2.LatLng): + Raw vehicle location (unprocessed by + road-snapper). + raw_location_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp associated with the raw location. + raw_location_sensor (google.maps.fleetengine_v1.types.LocationSensor): + Source of the raw location. Defaults to ``GPS``. + raw_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``raw_location`` as a radius, in meters. + supplemental_location (google.type.latlng_pb2.LatLng): + Supplemental location provided by the + integrating app. + supplemental_location_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp associated with the supplemental + location. + supplemental_location_sensor (google.maps.fleetengine_v1.types.LocationSensor): + Source of the supplemental location. Defaults to + ``CUSTOMER_SUPPLIED_LOCATION``. + supplemental_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): + Accuracy of ``supplemental_location`` as a radius, in + meters. + road_snapped (bool): + Deprecated: Use ``is_road_snapped`` instead. + """ + + location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + horizontal_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=8, + message=wrappers_pb2.DoubleValue, + ) + latlng_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=22, + message=wrappers_pb2.DoubleValue, + ) + heading: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int32Value, + ) + bearing_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=10, + message=wrappers_pb2.DoubleValue, + ) + heading_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=23, + message=wrappers_pb2.DoubleValue, + ) + altitude: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.DoubleValue, + ) + vertical_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=9, + message=wrappers_pb2.DoubleValue, + ) + altitude_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=24, + message=wrappers_pb2.DoubleValue, + ) + speed_kmph: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int32Value, + ) + speed: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.DoubleValue, + ) + speed_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=7, + message=wrappers_pb2.DoubleValue, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + server_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=13, + message=timestamp_pb2.Timestamp, + ) + location_sensor: 'LocationSensor' = proto.Field( + proto.ENUM, + number=11, + enum='LocationSensor', + ) + is_road_snapped: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=27, + message=wrappers_pb2.BoolValue, + ) + is_gps_sensor_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=12, + message=wrappers_pb2.BoolValue, + ) + time_since_update: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=14, + message=wrappers_pb2.Int32Value, + ) + num_stale_updates: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=15, + message=wrappers_pb2.Int32Value, + ) + raw_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=16, + message=latlng_pb2.LatLng, + ) + raw_location_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=17, + message=timestamp_pb2.Timestamp, + ) + raw_location_sensor: 'LocationSensor' = proto.Field( + proto.ENUM, + number=28, + enum='LocationSensor', + ) + raw_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=25, + message=wrappers_pb2.DoubleValue, + ) + supplemental_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=18, + message=latlng_pb2.LatLng, + ) + supplemental_location_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + supplemental_location_sensor: 'LocationSensor' = proto.Field( + proto.ENUM, + number=20, + enum='LocationSensor', + ) + supplemental_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( + proto.MESSAGE, + number=21, + message=wrappers_pb2.DoubleValue, + ) + road_snapped: bool = proto.Field( + proto.BOOL, + number=26, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py new file mode 100644 index 000000000000..6cc60e782c23 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py @@ -0,0 +1,168 @@ +# -*- 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='maps.fleetengine.v1', + manifest={ + 'RequestHeader', + }, +) + + +class RequestHeader(proto.Message): + r"""A RequestHeader contains fields common to all Fleet Engine + RPC requests. + + Attributes: + language_code (str): + The BCP-47 language code, such as en-US or sr-Latn. For more + information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + If none is specified, the response may be in any language, + with a preference for English if such a name exists. Field + value example: ``en-US``. + region_code (str): + Required. CLDR region code of the region where the request + originates. Field value example: ``US``. + sdk_version (str): + Version of the calling SDK, if applicable. The version + format is "major.minor.patch", example: ``1.1.2``. + os_version (str): + Version of the operating system on which the calling SDK is + running. Field value examples: ``4.4.1``, ``12.1``. + device_model (str): + Model of the device on which the calling SDK is running. + Field value examples: ``iPhone12,1``, ``SM-G920F``. + sdk_type (google.maps.fleetengine_v1.types.RequestHeader.SdkType): + The type of SDK sending the request. + maps_sdk_version (str): + Version of the MapSDK which the calling SDK depends on, if + applicable. The version format is "major.minor.patch", + example: ``5.2.1``. + nav_sdk_version (str): + Version of the NavSDK which the calling SDK depends on, if + applicable. The version format is "major.minor.patch", + example: ``2.1.0``. + platform (google.maps.fleetengine_v1.types.RequestHeader.Platform): + Platform of the calling SDK. + manufacturer (str): + Manufacturer of the Android device from the calling SDK, + only applicable for the Android SDKs. Field value example: + ``Samsung``. + android_api_level (int): + Android API level of the calling SDK, only applicable for + the Android SDKs. Field value example: ``23``. + trace_id (str): + Optional ID that can be provided for logging + purposes in order to identify the request. + """ + class SdkType(proto.Enum): + r"""Possible types of SDK. + + Values: + SDK_TYPE_UNSPECIFIED (0): + The default value. This value is used if the ``sdk_type`` is + omitted. + CONSUMER (1): + The calling SDK is Consumer. + DRIVER (2): + The calling SDK is Driver. + JAVASCRIPT (3): + The calling SDK is JavaScript. + """ + SDK_TYPE_UNSPECIFIED = 0 + CONSUMER = 1 + DRIVER = 2 + JAVASCRIPT = 3 + + class Platform(proto.Enum): + r"""The platform of the calling SDK. + + Values: + PLATFORM_UNSPECIFIED (0): + The default value. This value is used if the + platform is omitted. + ANDROID (1): + The request is coming from Android. + IOS (2): + The request is coming from iOS. + WEB (3): + The request is coming from the web. + """ + PLATFORM_UNSPECIFIED = 0 + ANDROID = 1 + IOS = 2 + WEB = 3 + + language_code: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + sdk_version: str = proto.Field( + proto.STRING, + number=3, + ) + os_version: str = proto.Field( + proto.STRING, + number=4, + ) + device_model: str = proto.Field( + proto.STRING, + number=5, + ) + sdk_type: SdkType = proto.Field( + proto.ENUM, + number=6, + enum=SdkType, + ) + maps_sdk_version: str = proto.Field( + proto.STRING, + number=7, + ) + nav_sdk_version: str = proto.Field( + proto.STRING, + number=8, + ) + platform: Platform = proto.Field( + proto.ENUM, + number=9, + enum=Platform, + ) + manufacturer: str = proto.Field( + proto.STRING, + number=10, + ) + android_api_level: int = proto.Field( + proto.INT32, + number=11, + ) + trace_id: str = proto.Field( + proto.STRING, + number=12, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py new file mode 100644 index 000000000000..c67d29281d61 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py @@ -0,0 +1,108 @@ +# -*- 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='maps.fleetengine.v1', + manifest={ + 'SpeedReadingInterval', + 'ConsumableTrafficPolyline', + }, +) + + +class SpeedReadingInterval(proto.Message): + r"""Traffic density indicator on a contiguous segment of a 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. + + Attributes: + start_polyline_point_index (int): + The starting index of this interval in the + path. In JSON, when the index is 0, the field + will appear to be unpopulated. + end_polyline_point_index (int): + The ending index of this interval in the + path. In JSON, when the index is 0, the field + will appear to be unpopulated. + speed (google.maps.fleetengine_v1.types.SpeedReadingInterval.Speed): + Traffic speed in this interval. + """ + class Speed(proto.Enum): + r"""The classification of polyline speed based on traffic data. + + Values: + SPEED_UNSPECIFIED (0): + Default value. This value is unused. + NORMAL (1): + Normal speed, no slowdown is detected. + SLOW (2): + Slowdown detected, but no traffic jam formed. + TRAFFIC_JAM (3): + Traffic jam detected. + """ + SPEED_UNSPECIFIED = 0 + NORMAL = 1 + SLOW = 2 + TRAFFIC_JAM = 3 + + start_polyline_point_index: int = proto.Field( + proto.INT32, + number=1, + ) + end_polyline_point_index: int = proto.Field( + proto.INT32, + number=2, + ) + speed: Speed = proto.Field( + proto.ENUM, + number=3, + enum=Speed, + ) + + +class ConsumableTrafficPolyline(proto.Message): + r"""Traffic density along a Vehicle's path. + + Attributes: + speed_reading_interval (MutableSequence[google.maps.fleetengine_v1.types.SpeedReadingInterval]): + Traffic speed along the path from the + previous waypoint to the current waypoint. + encoded_path_to_waypoint (str): + The path the driver is taking from the previous waypoint to + the current waypoint. This path has landmarks in it so + clients can show traffic markers along the path (see + ``speed_reading_interval``). Decoding is not yet supported. + """ + + speed_reading_interval: MutableSequence['SpeedReadingInterval'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SpeedReadingInterval', + ) + encoded_path_to_waypoint: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py new file mode 100644 index 000000000000..911a0a2053c2 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import header as mf_header +from google.maps.fleetengine_v1.types import trips as mf_trips +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'CreateTripRequest', + 'GetTripRequest', + 'ReportBillableTripRequest', + 'UpdateTripRequest', + 'SearchTripsRequest', + 'SearchTripsResponse', + }, +) + + +class CreateTripRequest(proto.Message): + r"""CreateTrip request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + trip_id (str): + Required. Unique Trip ID. Subject to the following + restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form C] + (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII characters: + '/', ':', '?', ',', or '#'. + trip (google.maps.fleetengine_v1.types.Trip): + Required. Trip entity to create. + + When creating a Trip, the following fields are required: + + - ``trip_type`` + - ``pickup_point`` + + The following fields are used if you provide them: + + - ``number_of_passengers`` + - ``vehicle_id`` + - ``dropoff_point`` + - ``intermediate_destinations`` + - ``vehicle_waypoints`` + + All other Trip fields are ignored. For example, all trips + start with a ``trip_status`` of ``NEW`` even if you pass in + a ``trip_status`` of ``CANCELED`` in the creation request. + + Only ``EXCLUSIVE`` trips support + ``intermediate_destinations``. + + When ``vehicle_id`` is set for a shared trip, you must + supply the list of ``Trip.vehicle_waypoints`` to specify the + order of the remaining waypoints for the vehicle, otherwise + the waypoint order will be undetermined. + + When you specify ``Trip.vehicle_waypoints``, the list must + contain all the remaining waypoints of the vehicle's trips, + with no extra waypoints. You must order these waypoints such + that for a given trip, the pickup point is before + intermediate destinations, and all intermediate destinations + come before the drop-off point. An ``EXCLUSIVE`` trip's + waypoints must not interleave with any other trips. + + The ``trip_id``, ``waypoint_type`` and ``location`` fields + are used, and all other TripWaypoint fields in + ``vehicle_waypoints`` are ignored. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + trip_id: str = proto.Field( + proto.STRING, + number=5, + ) + trip: mf_trips.Trip = proto.Field( + proto.MESSAGE, + number=4, + message=mf_trips.Trip, + ) + + +class GetTripRequest(proto.Message): + r"""GetTrip request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + name (str): + Required. Must be in the format + ``providers/{provider}/trips/{trip}``. The provider must be + the Project ID (for example, ``sample-cloud-project``) of + the Google Cloud Project of which the service account making + this call is a member. + view (google.maps.fleetengine_v1.types.TripView): + The subset of Trip fields that should be + returned and their interpretation. + current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Trip.route`` or ``Trip.current_route_segment`` data are + retrieved. If route data are unchanged since this timestamp, + the route field is not set in the response. If a minimum is + unspecified, the route data are always retrieved. + remaining_waypoints_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Trip.remaining_waypoints`` are retrieved. If they are + unchanged since this timestamp, the ``remaining_waypoints`` + are not set in the response. If this field is unspecified, + ``remaining_waypoints`` is always retrieved. + route_format_type (google.maps.fleetengine_v1.types.PolylineFormatType): + The returned current route format, ``LAT_LNG_LIST_TYPE`` (in + ``Trip.route``), or ``ENCODED_POLYLINE_TYPE`` (in + ``Trip.current_route_segment``). The default is + ``LAT_LNG_LIST_TYPE``. + current_route_segment_traffic_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Trip.current_route_segment_traffic`` is retrieved. If + traffic data are unchanged since this timestamp, the + ``current_route_segment_traffic`` field is not set in the + response. If a minimum is unspecified, the traffic data are + always retrieved. Note that traffic is only available for + On-Demand Rides and Deliveries Solution customers. + remaining_waypoints_route_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Trip.remaining_waypoints.traffic_to_waypoint`` and + ``Trip.remaining_waypoints.path_to_waypoint`` data are + retrieved. If data are unchanged since this timestamp, the + fields above are not set in the response. If + ``remaining_waypoints_route_version`` is unspecified, + traffic and path are always retrieved. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + view: mf_trips.TripView = proto.Field( + proto.ENUM, + number=11, + enum=mf_trips.TripView, + ) + current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + remaining_waypoints_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + route_format_type: fleetengine.PolylineFormatType = proto.Field( + proto.ENUM, + number=8, + enum=fleetengine.PolylineFormatType, + ) + current_route_segment_traffic_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + remaining_waypoints_route_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +class ReportBillableTripRequest(proto.Message): + r"""ReportBillableTrip request message. + + Attributes: + name (str): + Required. Must be in the format + ``providers/{provider}/billableTrips/{billable_trip}``. The + provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + country_code (str): + Required. Two letter country code of the + country where the trip takes place. Price is + defined according to country code. + platform (google.maps.fleetengine_v1.types.BillingPlatformIdentifier): + The platform upon which the request was + issued. + related_ids (MutableSequence[str]): + The identifiers that are directly related to the trip being + reported. These are usually IDs (for example, session IDs) + of pre-booking operations done before the trip ID is + available. The number of ``related_ids`` is limited to 50. + solution_type (google.maps.fleetengine_v1.types.ReportBillableTripRequest.SolutionType): + The type of GMP product solution (for example, + ``ON_DEMAND_RIDESHARING_AND_DELIVERIES``) used for the + reported trip. + """ + class SolutionType(proto.Enum): + r"""Selector for different solution types of a reported trip. + + Values: + SOLUTION_TYPE_UNSPECIFIED (0): + The default value. For backwards-compatibility, the API will + use ``ON_DEMAND_RIDESHARING_AND_DELIVERIES`` by default + which is the first supported solution type. + ON_DEMAND_RIDESHARING_AND_DELIVERIES (1): + The solution is an on-demand ridesharing and + deliveries trip. + """ + SOLUTION_TYPE_UNSPECIFIED = 0 + ON_DEMAND_RIDESHARING_AND_DELIVERIES = 1 + + name: str = proto.Field( + proto.STRING, + number=2, + ) + country_code: str = proto.Field( + proto.STRING, + number=3, + ) + platform: mf_trips.BillingPlatformIdentifier = proto.Field( + proto.ENUM, + number=5, + enum=mf_trips.BillingPlatformIdentifier, + ) + related_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + solution_type: SolutionType = proto.Field( + proto.ENUM, + number=7, + enum=SolutionType, + ) + + +class UpdateTripRequest(proto.Message): + r"""UpdateTrip request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + name (str): + Required. Must be in the format + ``providers/{provider}/trips/{trip}``. The provider must be + the Project ID (for example, ``sample-consumer-project``) of + the Google Cloud Project of which the service account making + this call is a member. + trip (google.maps.fleetengine_v1.types.Trip): + Required. The Trip associated with the update. + + The following fields are maintained by the Fleet Engine. Do + not update them using Trip.update. + + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_traffic`` + - ``current_route_segment_traffic_version`` + - ``current_route_segment_version`` + - ``dropoff_time`` + - ``eta_to_next_waypoint`` + - ``intermediate_destinations_version`` + - ``last_location`` + - ``name`` + - ``number_of_passengers`` + - ``pickup_time`` + - ``remaining_distance_meters`` + - ``remaining_time_to_first_waypoint`` + - ``remaining_waypoints`` + - ``remaining_waypoints_version`` + - ``route`` + + When you update the ``Trip.vehicle_id`` for a shared trip, + you must supply the list of ``Trip.vehicle_waypoints`` to + specify the order of the remaining waypoints, otherwise the + order will be undetermined. + + When you specify ``Trip.vehicle_waypoints``, the list must + contain all the remaining waypoints of the vehicle's trips, + with no extra waypoints. You must order these waypoints such + that for a given trip, the pickup point is before + intermediate destinations, and all intermediate destinations + come before the drop-off point. An ``EXCLUSIVE`` trip's + waypoints must not interleave with any other trips. The + ``trip_id``, ``waypoint_type`` and ``location`` fields are + used, and all other TripWaypoint fields in + ``vehicle_waypoints`` are ignored. + + To avoid a race condition for trips with multiple + destinations, you should provide + ``Trip.intermediate_destinations_version`` when updating the + trip status to ``ENROUTE_TO_INTERMEDIATE_DESTINATION``. The + ``Trip.intermediate_destinations_version`` passed must be + consistent with Fleet Engine's version. If it isn't, the + request fails. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field mask indicating which fields in Trip to + update. The ``update_mask`` must contain at least one field. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + trip: mf_trips.Trip = proto.Field( + proto.MESSAGE, + number=4, + message=mf_trips.Trip, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class SearchTripsRequest(proto.Message): + r"""SearchTrips request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + vehicle_id (str): + The vehicle associated with the trips in the request. If + unspecified, the returned trips do not contain: + + - ``current_route_segment`` + - ``remaining_waypoints`` + - ``remaining_distance_meters`` + - ``eta_to_first_waypoint`` + active_trips_only (bool): + If set to true, the response includes Trips + that influence a driver's route. + page_size (int): + If not set, the server decides the number of + results to return. + page_token (str): + Set this to a value previously returned in the + ``SearchTripsResponse`` to continue from previous results. + minimum_staleness (google.protobuf.duration_pb2.Duration): + If specified, returns the trips that have not been updated + after the time ``(current - minimum_staleness)``. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + vehicle_id: str = proto.Field( + proto.STRING, + number=4, + ) + active_trips_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + page_size: int = proto.Field( + proto.INT32, + number=6, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + minimum_staleness: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class SearchTripsResponse(proto.Message): + r"""SearchTrips response message. + + Attributes: + trips (MutableSequence[google.maps.fleetengine_v1.types.Trip]): + The list of trips for the requested vehicle. + next_page_token (str): + Pass this token in the SearchTripsRequest to + page through list results. The API returns a + trip list on each call, and when no more results + remain the trip list is empty. + """ + + @property + def raw_page(self): + return self + + trips: MutableSequence[mf_trips.Trip] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=mf_trips.Trip, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py new file mode 100644 index 000000000000..7fd145d8cd69 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py @@ -0,0 +1,490 @@ +# -*- 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.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import traffic +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.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'TripStatus', + 'BillingPlatformIdentifier', + 'TripView', + 'Trip', + 'StopLocation', + }, +) + + +class TripStatus(proto.Enum): + r"""The status of a trip indicating its progression. + + Values: + UNKNOWN_TRIP_STATUS (0): + Default, used for unspecified or unrecognized + trip status. + NEW (1): + Newly created trip. + ENROUTE_TO_PICKUP (2): + The driver is on their way to the pickup + point. + ARRIVED_AT_PICKUP (3): + The driver has arrived at the pickup point. + ARRIVED_AT_INTERMEDIATE_DESTINATION (7): + The driver has arrived at an intermediate + destination and is waiting for the rider. + ENROUTE_TO_INTERMEDIATE_DESTINATION (8): + The driver is on their way to an intermediate + destination (not the dropoff point). + ENROUTE_TO_DROPOFF (4): + The driver has picked up the rider and is on + their way to the next destination. + COMPLETE (5): + The rider has been dropped off and the trip + is complete. + CANCELED (6): + The trip was canceled prior to pickup by the + driver, rider, or rideshare provider. + """ + UNKNOWN_TRIP_STATUS = 0 + NEW = 1 + ENROUTE_TO_PICKUP = 2 + ARRIVED_AT_PICKUP = 3 + ARRIVED_AT_INTERMEDIATE_DESTINATION = 7 + ENROUTE_TO_INTERMEDIATE_DESTINATION = 8 + ENROUTE_TO_DROPOFF = 4 + COMPLETE = 5 + CANCELED = 6 + + +class BillingPlatformIdentifier(proto.Enum): + r"""A set of values that indicate upon which platform the request + was issued. + + Values: + BILLING_PLATFORM_IDENTIFIER_UNSPECIFIED (0): + Default. Used for unspecified platforms. + SERVER (1): + The platform is a client server. + WEB (2): + The platform is a web browser. + ANDROID (3): + The platform is an Android mobile device. + IOS (4): + The platform is an IOS mobile device. + OTHERS (5): + Other platforms that are not listed in this + enumeration. + """ + BILLING_PLATFORM_IDENTIFIER_UNSPECIFIED = 0 + SERVER = 1 + WEB = 2 + ANDROID = 3 + IOS = 4 + OTHERS = 5 + + +class TripView(proto.Enum): + r"""Selector for different sets of Trip fields in a ``GetTrip`` + response. See `AIP-157 `__ for context. + Additional views are likely to be added. + + Values: + TRIP_VIEW_UNSPECIFIED (0): + The default value. For backwards-compatibility, the API will + default to an SDK view. To ensure stability and support, + customers are advised to select a ``TripView`` other than + ``SDK``. + SDK (1): + Includes fields that may not be interpretable + or supportable using publicly available + libraries. + JOURNEY_SHARING_V1S (2): + Trip fields are populated for the Journey + Sharing use case. This view is intended for + server-to-server communications. + """ + TRIP_VIEW_UNSPECIFIED = 0 + SDK = 1 + JOURNEY_SHARING_V1S = 2 + + +class Trip(proto.Message): + r"""Trip metadata. + + Attributes: + name (str): + Output only. In the format + "providers/{provider}/trips/{trip}". + vehicle_id (str): + ID of the vehicle making this trip. + trip_status (google.maps.fleetengine_v1.types.TripStatus): + Current status of the trip. + trip_type (google.maps.fleetengine_v1.types.TripType): + The type of the trip. + pickup_point (google.maps.fleetengine_v1.types.TerminalLocation): + Location where customer indicates they will + be picked up. + actual_pickup_point (google.maps.fleetengine_v1.types.StopLocation): + Input only. The actual location when and + where customer was picked up. This field is for + provider to provide feedback on actual pickup + information. + actual_pickup_arrival_point (google.maps.fleetengine_v1.types.StopLocation): + Input only. The actual time and location of + the driver arrival at the pickup point. + This field is for provider to provide feedback + on actual arrival information at the pickup + point. + pickup_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Either the estimated future time + when the rider(s) will be picked up, or the + actual time when they were picked up. + intermediate_destinations (MutableSequence[google.maps.fleetengine_v1.types.TerminalLocation]): + Intermediate stops in order that the trip + requests (in addition to pickup and dropoff). + Initially this will not be supported for shared + trips. + intermediate_destinations_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the last time the ``intermediate_destinations`` + was modified. Your server should cache this value and pass + it in ``UpdateTripRequest`` when update + ``intermediate_destination_index`` to ensure the + ``intermediate_destinations`` is not changed. + intermediate_destination_index (int): + When ``TripStatus`` is + ``ENROUTE_TO_INTERMEDIATE_DESTINATION``, a number between + [0..N-1] indicating which intermediate destination the + vehicle will cross next. When ``TripStatus`` is + ``ARRIVED_AT_INTERMEDIATE_DESTINATION``, a number between + [0..N-1] indicating which intermediate destination the + vehicle is at. The provider sets this value. If there are no + ``intermediate_destinations``, this field is ignored. + actual_intermediate_destination_arrival_points (MutableSequence[google.maps.fleetengine_v1.types.StopLocation]): + Input only. The actual time and location of + the driver's arrival at an intermediate + destination. This field is for provider to + provide feedback on actual arrival information + at intermediate destinations. + actual_intermediate_destinations (MutableSequence[google.maps.fleetengine_v1.types.StopLocation]): + Input only. The actual time and location when + and where the customer was picked up from an + intermediate destination. This field is for + provider to provide feedback on actual pickup + information at intermediate destinations. + dropoff_point (google.maps.fleetengine_v1.types.TerminalLocation): + Location where customer indicates they will + be dropped off. + actual_dropoff_point (google.maps.fleetengine_v1.types.StopLocation): + Input only. The actual time and location when + and where customer was dropped off. This field + is for provider to provide feedback on actual + dropoff information. + dropoff_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Either the estimated future time + when the rider(s) will be dropped off at the + final destination, or the actual time when they + were dropped off. + remaining_waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): + Output only. The full path from the current + location to the dropoff point, inclusive. This + path could include waypoints from other trips. + vehicle_waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): + This field supports manual ordering of the waypoints for the + trip. It contains all of the remaining waypoints for the + assigned vehicle, as well as the pickup and drop-off + waypoints for this trip. If the trip hasn't been assigned to + a vehicle, then Fleet Engine ignores this field. For privacy + reasons, this field is only populated by the server on + ``UpdateTrip`` and ``CreateTrip`` calls, NOT on ``GetTrip`` + calls. + route (MutableSequence[google.type.latlng_pb2.LatLng]): + Output only. Anticipated route for this trip to the first + entry in remaining_waypoints. Note that the first waypoint + may belong to a different trip. + current_route_segment (str): + Output only. An encoded path to the next + waypoint. + Note: This field is intended only for use by the + Driver SDK and Consumer SDK. Decoding is not yet + supported. + current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Indicates the last time the + route was modified. + Note: This field is intended only for use by the + Driver SDK and Consumer SDK. + current_route_segment_traffic (google.maps.fleetengine_v1.types.ConsumableTrafficPolyline): + Output only. Indicates the traffic conditions along the + ``current_route_segment`` when they're available. + + Note: This field is intended only for use by the Driver SDK + and Consumer SDK. + current_route_segment_traffic_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Indicates the last time the + ``current_route_segment_traffic`` was modified. + + Note: This field is intended only for use by the Driver SDK + and Consumer SDK. + current_route_segment_end_point (google.maps.fleetengine_v1.types.TripWaypoint): + Output only. The waypoint where ``current_route_segment`` + ends. + remaining_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + Output only. The remaining driving distance in the + ``current_route_segment`` field. The value is unspecified if + the trip is not assigned to a vehicle, or the trip is + completed or cancelled. + eta_to_first_waypoint (google.protobuf.timestamp_pb2.Timestamp): + Output only. The ETA to the next waypoint (the first entry + in the ``remaining_waypoints`` field). The value is + unspecified if the trip is not assigned to a vehicle, or the + trip is inactive (completed or cancelled). + remaining_time_to_first_waypoint (google.protobuf.duration_pb2.Duration): + Output only. The duration from when the Trip data is + returned to the time in ``Trip.eta_to_first_waypoint``. The + value is unspecified if the trip is not assigned to a + vehicle, or the trip is inactive (completed or cancelled). + remaining_waypoints_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Indicates the last time that + ``remaining_waypoints`` was changed (a waypoint was added, + removed, or changed). + remaining_waypoints_route_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Indicates the last time the + ``remaining_waypoints.path_to_waypoint`` and + ``remaining_waypoints.traffic_to_waypoint`` were modified. + Your client app should cache this value and pass it in + ``GetTripRequest`` to ensure the paths and traffic for + ``remaining_waypoints`` are only returned if updated. + number_of_passengers (int): + Immutable. Indicates the number of passengers on this trip + and does not include the driver. A vehicle must have + available capacity to be returned in a ``SearchVehicles`` + response. + last_location (google.maps.fleetengine_v1.types.VehicleLocation): + Output only. Indicates the last reported + location of the vehicle along the route. + last_location_snappable (bool): + Output only. Indicates whether the vehicle's + ``last_location`` can be snapped to the + current_route_segment. False if ``last_location`` or + ``current_route_segment`` doesn't exist. It is computed by + Fleet Engine. Any update from clients will be ignored. + view (google.maps.fleetengine_v1.types.TripView): + The subset of Trip fields that are populated + and how they should be interpreted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + vehicle_id: str = proto.Field( + proto.STRING, + number=2, + ) + trip_status: 'TripStatus' = proto.Field( + proto.ENUM, + number=3, + enum='TripStatus', + ) + trip_type: fleetengine.TripType = proto.Field( + proto.ENUM, + number=4, + enum=fleetengine.TripType, + ) + pickup_point: fleetengine.TerminalLocation = proto.Field( + proto.MESSAGE, + number=5, + message=fleetengine.TerminalLocation, + ) + actual_pickup_point: 'StopLocation' = proto.Field( + proto.MESSAGE, + number=22, + message='StopLocation', + ) + actual_pickup_arrival_point: 'StopLocation' = proto.Field( + proto.MESSAGE, + number=32, + message='StopLocation', + ) + pickup_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + intermediate_destinations: MutableSequence[fleetengine.TerminalLocation] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=fleetengine.TerminalLocation, + ) + intermediate_destinations_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=25, + message=timestamp_pb2.Timestamp, + ) + intermediate_destination_index: int = proto.Field( + proto.INT32, + number=15, + ) + actual_intermediate_destination_arrival_points: MutableSequence['StopLocation'] = proto.RepeatedField( + proto.MESSAGE, + number=33, + message='StopLocation', + ) + actual_intermediate_destinations: MutableSequence['StopLocation'] = proto.RepeatedField( + proto.MESSAGE, + number=34, + message='StopLocation', + ) + dropoff_point: fleetengine.TerminalLocation = proto.Field( + proto.MESSAGE, + number=7, + message=fleetengine.TerminalLocation, + ) + actual_dropoff_point: 'StopLocation' = proto.Field( + proto.MESSAGE, + number=23, + message='StopLocation', + ) + dropoff_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + remaining_waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message=fleetengine.TripWaypoint, + ) + vehicle_waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message=fleetengine.TripWaypoint, + ) + route: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=latlng_pb2.LatLng, + ) + current_route_segment: str = proto.Field( + proto.STRING, + number=21, + ) + current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=17, + message=timestamp_pb2.Timestamp, + ) + current_route_segment_traffic: traffic.ConsumableTrafficPolyline = proto.Field( + proto.MESSAGE, + number=28, + message=traffic.ConsumableTrafficPolyline, + ) + current_route_segment_traffic_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=30, + message=timestamp_pb2.Timestamp, + ) + current_route_segment_end_point: fleetengine.TripWaypoint = proto.Field( + proto.MESSAGE, + number=24, + message=fleetengine.TripWaypoint, + ) + remaining_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=12, + message=wrappers_pb2.Int32Value, + ) + eta_to_first_waypoint: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=13, + message=timestamp_pb2.Timestamp, + ) + remaining_time_to_first_waypoint: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=27, + message=duration_pb2.Duration, + ) + remaining_waypoints_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + remaining_waypoints_route_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=29, + message=timestamp_pb2.Timestamp, + ) + number_of_passengers: int = proto.Field( + proto.INT32, + number=10, + ) + last_location: fleetengine.VehicleLocation = proto.Field( + proto.MESSAGE, + number=11, + message=fleetengine.VehicleLocation, + ) + last_location_snappable: bool = proto.Field( + proto.BOOL, + number=26, + ) + view: 'TripView' = proto.Field( + proto.ENUM, + number=31, + enum='TripView', + ) + + +class StopLocation(proto.Message): + r"""The actual location where a stop (pickup/dropoff) happened. + + Attributes: + point (google.type.latlng_pb2.LatLng): + Required. Denotes the actual location. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + Indicates when the stop happened. + stop_time (google.protobuf.timestamp_pb2.Timestamp): + Input only. Deprecated. Use the timestamp + field. + """ + + point: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + stop_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py new file mode 100644 index 000000000000..359753c644e4 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py @@ -0,0 +1,1047 @@ +# -*- 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.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import header as mf_header +from google.maps.fleetengine_v1.types import vehicles as mf_vehicles +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'CreateVehicleRequest', + 'GetVehicleRequest', + 'UpdateVehicleRequest', + 'UpdateVehicleAttributesRequest', + 'UpdateVehicleAttributesResponse', + 'SearchVehiclesRequest', + 'SearchVehiclesResponse', + 'ListVehiclesRequest', + 'ListVehiclesResponse', + 'Waypoint', + 'VehicleMatch', + 'VehicleAttributeList', + }, +) + + +class CreateVehicleRequest(proto.Message): + r"""``CreateVehicle`` request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + vehicle_id (str): + Required. Unique Vehicle ID. Subject to the following + restrictions: + + - Must be a valid Unicode string. + - Limited to a maximum length of 64 characters. + - Normalized according to [Unicode Normalization Form C] + (http://www.unicode.org/reports/tr15/). + - May not contain any of the following ASCII characters: + '/', ':', '?', ',', or '#'. + vehicle (google.maps.fleetengine_v1.types.Vehicle): + Required. The Vehicle entity to create. When creating a + Vehicle, the following fields are required: + + - ``vehicleState`` + - ``supportedTripTypes`` + - ``maximumCapacity`` + - ``vehicleType`` + + When creating a Vehicle, the following fields are ignored: + + - ``name`` + - ``currentTrips`` + - ``availableCapacity`` + - ``current_route_segment`` + - ``current_route_segment_end_point`` + - ``current_route_segment_version`` + - ``current_route_segment_traffic`` + - ``route`` + - ``waypoints`` + - ``waypoints_version`` + - ``remaining_distance_meters`` + - ``remaining_time_seconds`` + - ``eta_to_next_waypoint`` + - ``navigation_status`` + + All other fields are optional and used if provided. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + vehicle_id: str = proto.Field( + proto.STRING, + number=4, + ) + vehicle: mf_vehicles.Vehicle = proto.Field( + proto.MESSAGE, + number=5, + message=mf_vehicles.Vehicle, + ) + + +class GetVehicleRequest(proto.Message): + r"""``GetVehicle`` request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + name (str): + Required. Must be in the format + ``providers/{provider}/vehicles/{vehicle}``. The provider + must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Vehicle.current_route_segment`` is retrieved. If the route + is unchanged since this timestamp, the + ``current_route_segment`` field is not set in the response. + If a minimum is unspecified, the ``current_route_segment`` + is always retrieved. + waypoints_version (google.protobuf.timestamp_pb2.Timestamp): + Indicates the minimum timestamp (exclusive) for which + ``Vehicle.waypoints`` data is retrieved. If the waypoints + are unchanged since this timestamp, the + ``vehicle.waypoints`` data is not set in the response. If + this field is unspecified, ``vehicle.waypoints`` is always + retrieved. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + waypoints_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class UpdateVehicleRequest(proto.Message): + r"""\`UpdateVehicle request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + name (str): + Required. Must be in the format + ``providers/{provider}/vehicles/{vehicle}``. The {provider} + must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + vehicle (google.maps.fleetengine_v1.types.Vehicle): + Required. The ``Vehicle`` entity values to apply. When + updating a ``Vehicle``, the following fields may not be + updated as they are managed by the server. + + - ``available_capacity`` + - ``current_route_segment_version`` + - ``current_trips`` + - ``name`` + - ``waypoints_version`` + + If the ``attributes`` field is updated, **all** the + vehicle's attributes are replaced with the attributes + provided in the request. If you want to update only some + attributes, see the ``UpdateVehicleAttributes`` method. + + Likewise, the ``waypoints`` field can be updated, but must + contain all the waypoints currently on the vehicle, and no + other waypoints. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. A field mask indicating which fields of the + ``Vehicle`` to update. At least one field name must be + provided. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + vehicle: mf_vehicles.Vehicle = proto.Field( + proto.MESSAGE, + number=4, + message=mf_vehicles.Vehicle, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateVehicleAttributesRequest(proto.Message): + r"""``UpdateVehicleAttributes`` request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + name (str): + Required. Must be in the format + ``providers/{provider}/vehicles/{vehicle}``. The provider + must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): + Required. The vehicle attributes to update. + Unmentioned attributes are not altered or + removed. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=fleetengine.VehicleAttribute, + ) + + +class UpdateVehicleAttributesResponse(proto.Message): + r"""``UpdateVehicleAttributes`` response message. + + Attributes: + attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): + Required. The updated full list of vehicle + attributes, including new, altered, and + untouched attributes. + """ + + attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=fleetengine.VehicleAttribute, + ) + + +class SearchVehiclesRequest(proto.Message): + r"""``SearchVehicles`` request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + pickup_point (google.maps.fleetengine_v1.types.TerminalLocation): + Required. The pickup point to search near. + dropoff_point (google.maps.fleetengine_v1.types.TerminalLocation): + The customer's intended dropoff location. The field is + required if ``trip_types`` contains ``TripType.SHARED``. + pickup_radius_meters (int): + Required. Defines the vehicle search radius + around the pickup point. Only vehicles within + the search radius will be returned. Value must + be between 400 and 10000 meters (inclusive). + count (int): + Required. Specifies the maximum number of + vehicles to return. The value must be between 1 + and 50 (inclusive). + minimum_capacity (int): + Required. Specifies the number of passengers + being considered for a trip. The value must be + greater than or equal to one. The driver is not + considered in the capacity value. + trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): + Required. Represents the type of proposed trip. Must include + exactly one type. ``UNKNOWN_TRIP_TYPE`` is not allowed. + Restricts the search to only those vehicles that can support + that trip type. + maximum_staleness (google.protobuf.duration_pb2.Duration): + Restricts the search to only those vehicles + that have sent location updates to Fleet Engine + within the specified duration. Stationary + vehicles still transmitting their locations are + not considered stale. If this field is not set, + the server uses five minutes as the default + value. + vehicle_types (MutableSequence[google.maps.fleetengine_v1.types.Vehicle.VehicleType]): + Required. Restricts the search to vehicles with one of the + specified types. At least one vehicle type must be + specified. VehicleTypes with a category of ``UNKNOWN`` are + not allowed. + required_attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): + Callers can form complex logical operations using any + combination of the ``required_attributes``, + ``required_one_of_attributes``, and + ``required_one_of_attribute_sets`` fields. + + ``required_attributes`` is a list; + ``required_one_of_attributes`` uses a message which allows a + list of lists. In combination, the two fields allow the + composition of this expression: + + :: + + (required_attributes[0] AND required_attributes[1] AND ...) + AND + (required_one_of_attributes[0][0] OR required_one_of_attributes[0][1] OR + ...) + AND + (required_one_of_attributes[1][0] OR required_one_of_attributes[1][1] OR + ...) + + Restricts the search to only those vehicles with the + specified attributes. This field is a conjunction/AND + operation. A max of 50 required_attributes is allowed. This + matches the maximum number of attributes allowed on a + vehicle. + required_one_of_attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttributeList]): + Restricts the search to only those vehicles with at least + one of the specified attributes in each + ``VehicleAttributeList``. Within each list, a vehicle must + match at least one of the attributes. This field is an + inclusive disjunction/OR operation in each + ``VehicleAttributeList`` and a conjunction/AND operation + across the collection of ``VehicleAttributeList``. + required_one_of_attribute_sets (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttributeList]): + ``required_one_of_attribute_sets`` provides additional + functionality. + + Similar to ``required_one_of_attributes``, + ``required_one_of_attribute_sets`` uses a message which + allows a list of lists, allowing expressions such as this + one: + + :: + + (required_attributes[0] AND required_attributes[1] AND ...) + AND + ( + (required_one_of_attribute_sets[0][0] AND + required_one_of_attribute_sets[0][1] AND + ...) + OR + (required_one_of_attribute_sets[1][0] AND + required_one_of_attribute_sets[1][1] AND + ...) + ) + + Restricts the search to only those vehicles with all the + attributes in a ``VehicleAttributeList``. Within each list, + a vehicle must match all of the attributes. This field is a + conjunction/AND operation in each ``VehicleAttributeList`` + and inclusive disjunction/OR operation across the collection + of ``VehicleAttributeList``. + order_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): + Required. Specifies the desired ordering + criterion for results. + include_back_to_back (bool): + This indicates if vehicles with a single active trip are + eligible for this search. This field is only used when + ``current_trips_present`` is unspecified. When + ``current_trips_present`` is unspecified and this field is + ``false``, vehicles with assigned trips are excluded from + the search results. When ``current_trips_present`` is + unspecified and this field is ``true``, search results can + include vehicles with one active trip that has a status of + ``ENROUTE_TO_DROPOFF``. When ``current_trips_present`` is + specified, this field cannot be set to true. + + The default value is ``false``. + trip_id (str): + Indicates the trip associated with this + ``SearchVehicleRequest``. + current_trips_present (google.maps.fleetengine_v1.types.SearchVehiclesRequest.CurrentTripsPresent): + This indicates if vehicles with active trips are eligible + for this search. This must be set to something other than + ``CURRENT_TRIPS_PRESENT_UNSPECIFIED`` if ``trip_type`` + includes ``SHARED``. + filter (str): + Optional. A filter query to apply when searching vehicles. + See http://aip.dev/160 for examples of the filter syntax. + + This field is designed to replace the + ``required_attributes``, ``required_one_of_attributes``, and + ``required_one_of_attributes_sets`` fields. If a non-empty + value is specified here, the following fields must be empty: + ``required_attributes``, ``required_one_of_attributes``, and + ``required_one_of_attributes_sets``. + + This filter functions as an AND clause with other + constraints, such as ``minimum_capacity`` or + ``vehicle_types``. + + Note that the only queries supported are on vehicle + attributes (for example, ``attributes. = `` or + ``attributes. = AND attributes. = ``). + The maximum number of restrictions allowed in a filter query + is 50. + + Also, all attributes are stored as strings, so the only + supported comparisons against attributes are string + comparisons. In order to compare against number or boolean + values, the values must be explicitly quoted to be treated + as strings (for example, ``attributes. = "10"`` or + ``attributes. = "true"``). + """ + class VehicleMatchOrder(proto.Enum): + r"""Specifies the order of the vehicle matches in the response. + + Values: + UNKNOWN_VEHICLE_MATCH_ORDER (0): + Default, used for unspecified or unrecognized + vehicle matches order. + PICKUP_POINT_ETA (1): + Ascending order by vehicle driving time to + the pickup point. + PICKUP_POINT_DISTANCE (2): + Ascending order by vehicle driving distance + to the pickup point. + DROPOFF_POINT_ETA (3): + Ascending order by vehicle driving time to + the dropoff point. This order can only be used + if the dropoff point is specified in the + request. + PICKUP_POINT_STRAIGHT_DISTANCE (4): + Ascending order by straight-line distance + from the vehicle's last reported location to the + pickup point. + COST (5): + Ascending order by the configured match cost. + Match cost is defined as a weighted calculation + between straight-line distance and ETA. Weights + are set with default values and can be modified + per customer. Please contact Google support if + these weights need to be modified for your + project. + """ + UNKNOWN_VEHICLE_MATCH_ORDER = 0 + PICKUP_POINT_ETA = 1 + PICKUP_POINT_DISTANCE = 2 + DROPOFF_POINT_ETA = 3 + PICKUP_POINT_STRAIGHT_DISTANCE = 4 + COST = 5 + + class CurrentTripsPresent(proto.Enum): + r"""Specifies the types of restrictions on a vehicle's current + trips. + + Values: + CURRENT_TRIPS_PRESENT_UNSPECIFIED (0): + The availability of vehicles with trips present is governed + by the ``include_back_to_back`` field. + NONE (1): + Vehicles without trips can appear in search results. When + this value is used, ``include_back_to_back`` cannot be + ``true``. + ANY (2): + Vehicles with at most 5 current trips and 10 waypoints are + included in the search results. When this value is used, + ``include_back_to_back`` cannot be ``true``. + """ + CURRENT_TRIPS_PRESENT_UNSPECIFIED = 0 + NONE = 1 + ANY = 2 + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=1, + message=mf_header.RequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + pickup_point: fleetengine.TerminalLocation = proto.Field( + proto.MESSAGE, + number=4, + message=fleetengine.TerminalLocation, + ) + dropoff_point: fleetengine.TerminalLocation = proto.Field( + proto.MESSAGE, + number=5, + message=fleetengine.TerminalLocation, + ) + pickup_radius_meters: int = proto.Field( + proto.INT32, + number=6, + ) + count: int = proto.Field( + proto.INT32, + number=7, + ) + minimum_capacity: int = proto.Field( + proto.INT32, + number=8, + ) + trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( + proto.ENUM, + number=9, + enum=fleetengine.TripType, + ) + maximum_staleness: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=10, + message=duration_pb2.Duration, + ) + vehicle_types: MutableSequence[mf_vehicles.Vehicle.VehicleType] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=mf_vehicles.Vehicle.VehicleType, + ) + required_attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=fleetengine.VehicleAttribute, + ) + required_one_of_attributes: MutableSequence['VehicleAttributeList'] = proto.RepeatedField( + proto.MESSAGE, + number=15, + message='VehicleAttributeList', + ) + required_one_of_attribute_sets: MutableSequence['VehicleAttributeList'] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message='VehicleAttributeList', + ) + order_by: VehicleMatchOrder = proto.Field( + proto.ENUM, + number=13, + enum=VehicleMatchOrder, + ) + include_back_to_back: bool = proto.Field( + proto.BOOL, + number=18, + ) + trip_id: str = proto.Field( + proto.STRING, + number=19, + ) + current_trips_present: CurrentTripsPresent = proto.Field( + proto.ENUM, + number=21, + enum=CurrentTripsPresent, + ) + filter: str = proto.Field( + proto.STRING, + number=22, + ) + + +class SearchVehiclesResponse(proto.Message): + r"""``SearchVehicles`` response message. + + Attributes: + matches (MutableSequence[google.maps.fleetengine_v1.types.VehicleMatch]): + List of vehicles that match the ``SearchVehiclesRequest`` + criteria, ordered according to + ``SearchVehiclesRequest.order_by`` field. + """ + + matches: MutableSequence['VehicleMatch'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='VehicleMatch', + ) + + +class ListVehiclesRequest(proto.Message): + r"""``ListVehicles`` request message. + + Attributes: + header (google.maps.fleetengine_v1.types.RequestHeader): + The standard Fleet Engine request header. + parent (str): + Required. Must be in the format ``providers/{provider}``. + The provider must be the Project ID (for example, + ``sample-cloud-project``) of the Google Cloud Project of + which the service account making this call is a member. + page_size (int): + The maximum number of vehicles to return. + Default value: 100. + page_token (str): + The value of the ``next_page_token`` provided by a previous + call to ``ListVehicles`` so that you can paginate through + groups of vehicles. The value is undefined if the filter + criteria of the request is not the same as the filter + criteria for the previous call to ``ListVehicles``. + minimum_capacity (google.protobuf.wrappers_pb2.Int32Value): + Specifies the required minimum capacity of the vehicle. All + vehicles returned will have a ``maximum_capacity`` greater + than or equal to this value. If set, must be greater or + equal to 0. + trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): + Restricts the response to vehicles that + support at least one of the specified trip + types. + maximum_staleness (google.protobuf.duration_pb2.Duration): + Restricts the response to vehicles that have + sent location updates to Fleet Engine within the + specified duration. Stationary vehicles still + transmitting their locations are not considered + stale. If present, must be a valid positive + duration. + vehicle_type_categories (MutableSequence[google.maps.fleetengine_v1.types.Vehicle.VehicleType.Category]): + Required. Restricts the response to vehicles with one of the + specified type categories. ``UNKNOWN`` is not allowed. + required_attributes (MutableSequence[str]): + Callers can form complex logical operations using any + combination of the ``required_attributes``, + ``required_one_of_attributes``, and + ``required_one_of_attribute_sets`` fields. + + ``required_attributes`` is a list; + ``required_one_of_attributes`` uses a message which allows a + list of lists. In combination, the two fields allow the + composition of this expression: + + :: + + (required_attributes[0] AND required_attributes[1] AND ...) + AND + (required_one_of_attributes[0][0] OR required_one_of_attributes[0][1] OR + ...) + AND + (required_one_of_attributes[1][0] OR required_one_of_attributes[1][1] OR + ...) + + Restricts the response to vehicles with the specified + attributes. This field is a conjunction/AND operation. A max + of 50 required_attributes is allowed. This matches the + maximum number of attributes allowed on a vehicle. Each + repeated string should be of the format "key:value". + required_one_of_attributes (MutableSequence[str]): + Restricts the response to vehicles with at least one of the + specified attributes in each ``VehicleAttributeList``. + Within each list, a vehicle must match at least one of the + attributes. This field is an inclusive disjunction/OR + operation in each ``VehicleAttributeList`` and a + conjunction/AND operation across the collection of + ``VehicleAttributeList``. Each repeated string should be of + the format "key1:value1|key2:value2|key3:value3". + required_one_of_attribute_sets (MutableSequence[str]): + ``required_one_of_attribute_sets`` provides additional + functionality. + + Similar to ``required_one_of_attributes``, + ``required_one_of_attribute_sets`` uses a message which + allows a list of lists, allowing expressions such as this + one: + + :: + + (required_attributes[0] AND required_attributes[1] AND ...) + AND + ( + (required_one_of_attribute_sets[0][0] AND + required_one_of_attribute_sets[0][1] AND + ...) + OR + (required_one_of_attribute_sets[1][0] AND + required_one_of_attribute_sets[1][1] AND + ...) + ) + + Restricts the response to vehicles that match all the + attributes in a ``VehicleAttributeList``. Within each list, + a vehicle must match all of the attributes. This field is a + conjunction/AND operation in each ``VehicleAttributeList`` + and inclusive disjunction/OR operation across the collection + of ``VehicleAttributeList``. Each repeated string should be + of the format "key1:value1|key2:value2|key3:value3". + vehicle_state (google.maps.fleetengine_v1.types.VehicleState): + Restricts the response to vehicles that have + this vehicle state. + on_trip_only (bool): + Only return the vehicles with current + trip(s). + filter (str): + Optional. A filter query to apply when listing vehicles. See + http://aip.dev/160 for examples of the filter syntax. + + This field is designed to replace the + ``required_attributes``, ``required_one_of_attributes``, and + ``required_one_of_attributes_sets`` fields. If a non-empty + value is specified here, the following fields must be empty: + ``required_attributes``, ``required_one_of_attributes``, and + ``required_one_of_attributes_sets``. + + This filter functions as an AND clause with other + constraints, such as ``vehicle_state`` or ``on_trip_only``. + + Note that the only queries supported are on vehicle + attributes (for example, ``attributes. = `` or + ``attributes. = AND attributes. = ``). + The maximum number of restrictions allowed in a filter query + is 50. + + Also, all attributes are stored as strings, so the only + supported comparisons against attributes are string + comparisons. In order to compare against number or boolean + values, the values must be explicitly quoted to be treated + as strings (for example, ``attributes. = "10"`` or + ``attributes. = "true"``). + viewport (google.geo.type.types.Viewport): + Optional. A filter that limits the vehicles + returned to those whose last known location was + in the rectangular area defined by the viewport. + """ + + header: mf_header.RequestHeader = proto.Field( + proto.MESSAGE, + number=12, + message=mf_header.RequestHeader, + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + minimum_capacity: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.Int32Value, + ) + trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( + proto.ENUM, + number=7, + enum=fleetengine.TripType, + ) + maximum_staleness: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + vehicle_type_categories: MutableSequence[mf_vehicles.Vehicle.VehicleType.Category] = proto.RepeatedField( + proto.ENUM, + number=9, + enum=mf_vehicles.Vehicle.VehicleType.Category, + ) + required_attributes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + required_one_of_attributes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=13, + ) + required_one_of_attribute_sets: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=15, + ) + vehicle_state: mf_vehicles.VehicleState = proto.Field( + proto.ENUM, + number=11, + enum=mf_vehicles.VehicleState, + ) + on_trip_only: bool = proto.Field( + proto.BOOL, + number=14, + ) + filter: str = proto.Field( + proto.STRING, + number=16, + ) + viewport: ggt_viewport.Viewport = proto.Field( + proto.MESSAGE, + number=17, + message=ggt_viewport.Viewport, + ) + + +class ListVehiclesResponse(proto.Message): + r"""``ListVehicles`` response message. + + Attributes: + vehicles (MutableSequence[google.maps.fleetengine_v1.types.Vehicle]): + Vehicles matching the criteria in the request. The maximum + number of vehicles returned is determined by the + ``page_size`` field in the request. + next_page_token (str): + Token to retrieve the next page of vehicles, + or empty if there are no more vehicles that meet + the request criteria. + total_size (int): + Required. Total number of vehicles matching + the request criteria across all pages. + """ + + @property + def raw_page(self): + return self + + vehicles: MutableSequence[mf_vehicles.Vehicle] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=mf_vehicles.Vehicle, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT64, + number=3, + ) + + +class Waypoint(proto.Message): + r"""Describes intermediate points along a route for a ``VehicleMatch`` + in a ``SearchVehiclesResponse``. This concept is represented as a + ``TripWaypoint`` in all other endpoints. + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + The location of this waypoint. + eta (google.protobuf.timestamp_pb2.Timestamp): + The estimated time that the vehicle will + arrive at this waypoint. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + eta: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class VehicleMatch(proto.Message): + r"""Contains the vehicle and related estimates for a vehicle that match + the points of active trips for the vehicle + ``SearchVehiclesRequest``. + + Attributes: + vehicle (google.maps.fleetengine_v1.types.Vehicle): + Required. A vehicle that matches the request. + vehicle_pickup_eta (google.protobuf.timestamp_pb2.Timestamp): + The vehicle's driving ETA to the pickup point specified in + the request. An empty value indicates a failure in + calculating ETA for the vehicle. If + ``SearchVehiclesRequest.include_back_to_back`` was ``true`` + and this vehicle has an active trip, ``vehicle_pickup_eta`` + includes the time required to complete the current active + trip. + vehicle_pickup_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + The distance from the Vehicle's current + location to the pickup point specified in the + request, including any intermediate pickup or + dropoff points for existing trips. This distance + comprises the calculated driving (route) + distance, plus the straight line distance + between the navigation end point and the + requested pickup point. (The distance between + the navigation end point and the requested + pickup point is typically small.) An empty value + indicates an error in calculating the distance. + vehicle_pickup_straight_line_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + Required. The straight-line distance between + the vehicle and the pickup point specified in + the request. + vehicle_dropoff_eta (google.protobuf.timestamp_pb2.Timestamp): + The complete vehicle's driving ETA to the drop off point + specified in the request. The ETA includes stopping at any + waypoints before the ``dropoff_point`` specified in the + request. The value will only be populated when a drop off + point is specified in the request. An empty value indicates + an error calculating the ETA. + vehicle_pickup_to_dropoff_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + The vehicle's driving distance (in meters) from the pickup + point to the drop off point specified in the request. The + distance is only between the two points and does not include + the vehicle location or any other points that must be + visited before the vehicle visits either the pickup point or + dropoff point. The value will only be populated when a + ``dropoff_point`` is specified in the request. An empty + value indicates a failure in calculating the distance from + the pickup to drop off point specified in the request. + trip_type (google.maps.fleetengine_v1.types.TripType): + Required. The trip type of the request that + was used to calculate the ETA to the pickup + point. + vehicle_trips_waypoints (MutableSequence[google.maps.fleetengine_v1.types.Waypoint]): + The ordered list of waypoints used to + calculate the ETA. The list includes vehicle + location, the pickup points of active trips for + the vehicle, and the pickup points provided in + the request. An empty list indicates a failure + in calculating ETA for the vehicle. + vehicle_match_type (google.maps.fleetengine_v1.types.VehicleMatch.VehicleMatchType): + Type of the vehicle match. + requested_ordered_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): + The order requested for sorting vehicle matches. Equivalent + to ``ordered_by``. + ordered_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): + The order requested for sorting vehicle matches. Equivalent + to ``requested_ordered_by``. + """ + class VehicleMatchType(proto.Enum): + r"""Type of vehicle match. + + Values: + UNKNOWN (0): + Unknown vehicle match type + EXCLUSIVE (1): + The vehicle currently has no trip assigned to + it and can proceed to the pickup point. + BACK_TO_BACK (2): + The vehicle is currently assigned to a trip, + but can proceed to the pickup point after + completing the in-progress trip. ETA and + distance calculations take the existing trip + into account. + CARPOOL (3): + The vehicle has sufficient capacity for a + shared ride. + CARPOOL_BACK_TO_BACK (4): + The vehicle will finish its current, active + trip before proceeding to the pickup point. ETA + and distance calculations take the existing trip + into account. + """ + UNKNOWN = 0 + EXCLUSIVE = 1 + BACK_TO_BACK = 2 + CARPOOL = 3 + CARPOOL_BACK_TO_BACK = 4 + + vehicle: mf_vehicles.Vehicle = proto.Field( + proto.MESSAGE, + number=1, + message=mf_vehicles.Vehicle, + ) + vehicle_pickup_eta: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + vehicle_pickup_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int32Value, + ) + vehicle_pickup_straight_line_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=11, + message=wrappers_pb2.Int32Value, + ) + vehicle_dropoff_eta: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + vehicle_pickup_to_dropoff_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.Int32Value, + ) + trip_type: fleetengine.TripType = proto.Field( + proto.ENUM, + number=6, + enum=fleetengine.TripType, + ) + vehicle_trips_waypoints: MutableSequence['Waypoint'] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message='Waypoint', + ) + vehicle_match_type: VehicleMatchType = proto.Field( + proto.ENUM, + number=8, + enum=VehicleMatchType, + ) + requested_ordered_by: 'SearchVehiclesRequest.VehicleMatchOrder' = proto.Field( + proto.ENUM, + number=9, + enum='SearchVehiclesRequest.VehicleMatchOrder', + ) + ordered_by: 'SearchVehiclesRequest.VehicleMatchOrder' = proto.Field( + proto.ENUM, + number=10, + enum='SearchVehiclesRequest.VehicleMatchOrder', + ) + + +class VehicleAttributeList(proto.Message): + r"""A list-of-lists datatype for vehicle attributes. + + Attributes: + attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): + A list of attributes in this collection. + """ + + attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=fleetengine.VehicleAttribute, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py new file mode 100644 index 000000000000..c4662d189513 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py @@ -0,0 +1,580 @@ +# -*- 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.fleetengine_v1.types import fleetengine +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='maps.fleetengine.v1', + manifest={ + 'VehicleState', + 'LocationPowerSaveMode', + 'BatteryStatus', + 'PowerSource', + 'Vehicle', + 'BatteryInfo', + 'DeviceSettings', + 'LicensePlate', + 'VisualTrafficReportPolylineRendering', + 'TrafficPolylineData', + }, +) + + +class VehicleState(proto.Enum): + r"""The state of a ``Vehicle``. + + Values: + UNKNOWN_VEHICLE_STATE (0): + Default, used for unspecified or unrecognized + vehicle states. + OFFLINE (1): + The vehicle is not accepting new trips. Note: + the vehicle may continue to operate in this + state while completing a trip assigned to it. + ONLINE (2): + The vehicle is accepting new trips. + """ + UNKNOWN_VEHICLE_STATE = 0 + OFFLINE = 1 + ONLINE = 2 + + +class LocationPowerSaveMode(proto.Enum): + r"""How location features are configured to behave on the mobile + device when the devices "battery saver" feature is on. + (https://developer.android.com/reference/android/os/PowerManager#getLocationPowerSaveMode()) + + Values: + UNKNOWN_LOCATION_POWER_SAVE_MODE (0): + Undefined LocationPowerSaveMode + LOCATION_MODE_NO_CHANGE (1): + Either the location providers shouldn't be + affected by battery saver, or battery saver is + off. + LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF (2): + The GPS based location provider should be + disabled when battery saver is on and the device + is non-interactive. + LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF (3): + All location providers should be disabled + when battery saver is on and the device is + non-interactive. + LOCATION_MODE_FOREGROUND_ONLY (4): + All the location providers will be kept + available, but location fixes should only be + provided to foreground apps. + LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF (5): + Location will not be turned off, but + LocationManager will throttle all requests to + providers when the device is non-interactive. + """ + UNKNOWN_LOCATION_POWER_SAVE_MODE = 0 + LOCATION_MODE_NO_CHANGE = 1 + LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF = 2 + LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF = 3 + LOCATION_MODE_FOREGROUND_ONLY = 4 + LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF = 5 + + +class BatteryStatus(proto.Enum): + r"""Status of the battery, whether full or charging etc. + + Values: + UNKNOWN_BATTERY_STATUS (0): + Battery status unknown. + BATTERY_STATUS_CHARGING (1): + Battery is being charged. + BATTERY_STATUS_DISCHARGING (2): + Battery is discharging. + BATTERY_STATUS_FULL (3): + Battery is full. + BATTERY_STATUS_NOT_CHARGING (4): + Battery is not charging. + BATTERY_STATUS_POWER_LOW (5): + Battery is low on power. + """ + UNKNOWN_BATTERY_STATUS = 0 + BATTERY_STATUS_CHARGING = 1 + BATTERY_STATUS_DISCHARGING = 2 + BATTERY_STATUS_FULL = 3 + BATTERY_STATUS_NOT_CHARGING = 4 + BATTERY_STATUS_POWER_LOW = 5 + + +class PowerSource(proto.Enum): + r"""Type of the charger being used to charge the battery. + + Values: + UNKNOWN_POWER_SOURCE (0): + Power source unknown. + POWER_SOURCE_AC (1): + Power source is an AC charger. + POWER_SOURCE_USB (2): + Power source is a USB port. + POWER_SOURCE_WIRELESS (3): + Power source is wireless. + POWER_SOURCE_UNPLUGGED (4): + Battery is unplugged. + """ + UNKNOWN_POWER_SOURCE = 0 + POWER_SOURCE_AC = 1 + POWER_SOURCE_USB = 2 + POWER_SOURCE_WIRELESS = 3 + POWER_SOURCE_UNPLUGGED = 4 + + +class Vehicle(proto.Message): + r"""Vehicle metadata. + + Attributes: + name (str): + Output only. The unique name for this vehicle. The format is + ``providers/{provider}/vehicles/{vehicle}``. + vehicle_state (google.maps.fleetengine_v1.types.VehicleState): + The vehicle state. + supported_trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): + Trip types supported by this vehicle. + current_trips (MutableSequence[str]): + Output only. List of ``trip_id``'s for trips currently + assigned to this vehicle. + last_location (google.maps.fleetengine_v1.types.VehicleLocation): + Last reported location of the vehicle. + maximum_capacity (int): + The total numbers of riders this vehicle can + carry. The driver is not considered in this + value. This value must be greater than or equal + to one. + attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): + List of vehicle attributes. A vehicle can + have at most 100 attributes, and each attribute + must have a unique key. + vehicle_type (google.maps.fleetengine_v1.types.Vehicle.VehicleType): + Required. The type of this vehicle. Can be used to filter + vehicles in ``SearchVehicles`` results. Also influences ETA + and route calculations. + license_plate (google.maps.fleetengine_v1.types.LicensePlate): + License plate information for the vehicle. + route (MutableSequence[google.maps.fleetengine_v1.types.TerminalLocation]): + Deprecated: Use ``Vehicle.waypoints`` instead. + current_route_segment (str): + The polyline specifying the route the driver app intends to + take to the next waypoint. This list is also returned in + ``Trip.current_route_segment`` for all active trips assigned + to the vehicle. + + Note: This field is intended only for use by the Driver SDK. + Decoding is not yet supported. + current_route_segment_traffic (google.maps.fleetengine_v1.types.TrafficPolylineData): + Input only. Fleet Engine uses this + information to improve journey sharing. Note: + This field is intended only for use by the + Driver SDK. + current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when ``current_route_segment`` was set. It + can be stored by the client and passed in future + ``GetVehicle`` requests to prevent returning routes that + haven't changed. + current_route_segment_end_point (google.maps.fleetengine_v1.types.TripWaypoint): + The waypoint where ``current_route_segment`` ends. This can + be supplied by drivers on ``UpdateVehicle`` calls either as + a full trip waypoint, a waypoint ``LatLng``, or as the last + ``LatLng`` of the ``current_route_segment``. Fleet Engine + will then do its best to interpolate to an actual waypoint + if it is not fully specified. This field is ignored in + ``UpdateVehicle`` calls unless ``current_route_segment`` is + also specified. + remaining_distance_meters (google.protobuf.wrappers_pb2.Int32Value): + The remaining driving distance for the + ``current_route_segment``. This value is also returned in + ``Trip.remaining_distance_meters`` for all active trips + assigned to the vehicle. The value is unspecified if the + ``current_route_segment`` field is empty. + eta_to_first_waypoint (google.protobuf.timestamp_pb2.Timestamp): + The ETA to the first entry in the ``waypoints`` field. The + value is unspecified if the ``waypoints`` field is empty or + the ``Vehicle.current_route_segment`` field is empty. + + When updating a vehicle, ``remaining_time_seconds`` takes + precedence over ``eta_to_first_waypoint`` in the same + request. + remaining_time_seconds (google.protobuf.wrappers_pb2.Int32Value): + Input only. The remaining driving time for the + ``current_route_segment``. The value is unspecified if the + ``waypoints`` field is empty or the + ``Vehicle.current_route_segment`` field is empty. This value + should match ``eta_to_first_waypoint`` - ``current_time`` if + all parties are using the same clock. + + When updating a vehicle, ``remaining_time_seconds`` takes + precedence over ``eta_to_first_waypoint`` in the same + request. + waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): + The remaining waypoints assigned to this + Vehicle. + waypoints_version (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last time the ``waypoints`` field was updated. + Clients should cache this value and pass it in + ``GetVehicleRequest`` to ensure the ``waypoints`` field is + only returned if it is updated. + back_to_back_enabled (bool): + Indicates if the driver accepts back-to-back trips. If + ``true``, ``SearchVehicles`` may include the vehicle even if + it is currently assigned to a trip. The default value is + ``false``. + navigation_status (google.maps.fleetengine_v1.types.NavigationStatus): + The vehicle's navigation status. + device_settings (google.maps.fleetengine_v1.types.DeviceSettings): + Input only. Information about settings in the + mobile device being used by the driver. + """ + + class VehicleType(proto.Message): + r"""The type of vehicle. + + Attributes: + category (google.maps.fleetengine_v1.types.Vehicle.VehicleType.Category): + Vehicle type category + """ + class Category(proto.Enum): + r"""Vehicle type categories + + Values: + UNKNOWN (0): + Default, used for unspecified or unrecognized + vehicle categories. + AUTO (1): + An automobile. + TAXI (2): + Any vehicle that acts as a taxi (typically + licensed or regulated). + TRUCK (3): + Generally, a vehicle with a large storage + capacity. + TWO_WHEELER (4): + A motorcycle, moped, or other two-wheeled + vehicle + BICYCLE (5): + Human-powered transport. + PEDESTRIAN (6): + A human transporter, typically walking or + running, traveling along pedestrian pathways. + """ + UNKNOWN = 0 + AUTO = 1 + TAXI = 2 + TRUCK = 3 + TWO_WHEELER = 4 + BICYCLE = 5 + PEDESTRIAN = 6 + + category: 'Vehicle.VehicleType.Category' = proto.Field( + proto.ENUM, + number=1, + enum='Vehicle.VehicleType.Category', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + vehicle_state: 'VehicleState' = proto.Field( + proto.ENUM, + number=2, + enum='VehicleState', + ) + supported_trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=fleetengine.TripType, + ) + current_trips: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + last_location: fleetengine.VehicleLocation = proto.Field( + proto.MESSAGE, + number=5, + message=fleetengine.VehicleLocation, + ) + maximum_capacity: int = proto.Field( + proto.INT32, + number=6, + ) + attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=fleetengine.VehicleAttribute, + ) + vehicle_type: VehicleType = proto.Field( + proto.MESSAGE, + number=9, + message=VehicleType, + ) + license_plate: 'LicensePlate' = proto.Field( + proto.MESSAGE, + number=10, + message='LicensePlate', + ) + route: MutableSequence[fleetengine.TerminalLocation] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=fleetengine.TerminalLocation, + ) + current_route_segment: str = proto.Field( + proto.STRING, + number=20, + ) + current_route_segment_traffic: 'TrafficPolylineData' = proto.Field( + proto.MESSAGE, + number=28, + message='TrafficPolylineData', + ) + current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=15, + message=timestamp_pb2.Timestamp, + ) + current_route_segment_end_point: fleetengine.TripWaypoint = proto.Field( + proto.MESSAGE, + number=24, + message=fleetengine.TripWaypoint, + ) + remaining_distance_meters: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=18, + message=wrappers_pb2.Int32Value, + ) + eta_to_first_waypoint: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + remaining_time_seconds: wrappers_pb2.Int32Value = proto.Field( + proto.MESSAGE, + number=25, + message=wrappers_pb2.Int32Value, + ) + waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( + proto.MESSAGE, + number=22, + message=fleetengine.TripWaypoint, + ) + waypoints_version: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=16, + message=timestamp_pb2.Timestamp, + ) + back_to_back_enabled: bool = proto.Field( + proto.BOOL, + number=23, + ) + navigation_status: fleetengine.NavigationStatus = proto.Field( + proto.ENUM, + number=26, + enum=fleetengine.NavigationStatus, + ) + device_settings: 'DeviceSettings' = proto.Field( + proto.MESSAGE, + number=27, + message='DeviceSettings', + ) + + +class BatteryInfo(proto.Message): + r"""Information about the device's battery. + + Attributes: + battery_status (google.maps.fleetengine_v1.types.BatteryStatus): + Status of the battery, whether full or + charging etc. + power_source (google.maps.fleetengine_v1.types.PowerSource): + Status of battery power source. + battery_percentage (float): + Current battery percentage [0-100]. + """ + + battery_status: 'BatteryStatus' = proto.Field( + proto.ENUM, + number=1, + enum='BatteryStatus', + ) + power_source: 'PowerSource' = proto.Field( + proto.ENUM, + number=2, + enum='PowerSource', + ) + battery_percentage: float = proto.Field( + proto.FLOAT, + number=3, + ) + + +class DeviceSettings(proto.Message): + r"""Information about various settings on the mobile device. + + Attributes: + location_power_save_mode (google.maps.fleetengine_v1.types.LocationPowerSaveMode): + How location features are set to behave on + the device when battery saver is on. + is_power_save_mode (bool): + Whether the device is currently in power save + mode. + is_interactive (bool): + Whether the device is in an interactive + state. + battery_info (google.maps.fleetengine_v1.types.BatteryInfo): + Information about the battery state. + """ + + location_power_save_mode: 'LocationPowerSaveMode' = proto.Field( + proto.ENUM, + number=1, + enum='LocationPowerSaveMode', + ) + is_power_save_mode: bool = proto.Field( + proto.BOOL, + number=2, + ) + is_interactive: bool = proto.Field( + proto.BOOL, + number=3, + ) + battery_info: 'BatteryInfo' = proto.Field( + proto.MESSAGE, + number=4, + message='BatteryInfo', + ) + + +class LicensePlate(proto.Message): + r"""The license plate information of the Vehicle. To avoid + storing personally-identifiable information, only the minimum + information about the license plate is stored as part of the + entity. + + Attributes: + country_code (str): + Required. CLDR Country/Region Code. For example, ``US`` for + United States, or ``IN`` for India. + last_character (str): + The last digit of the license plate or "-1" to denote no + numeric value is present in the license plate. + + - "ABC 1234" -> "4" + - "AB 123 CD" -> "3" + - "ABCDEF" -> "-1". + """ + + country_code: str = proto.Field( + proto.STRING, + number=1, + ) + last_character: str = proto.Field( + proto.STRING, + number=2, + ) + + +class VisualTrafficReportPolylineRendering(proto.Message): + r"""Describes how clients should color one portion of the + polyline along the route. + + Attributes: + road_stretch (MutableSequence[google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering.RoadStretch]): + Optional. Road stretches that should be + rendered along the polyline. Stretches are + guaranteed to not overlap, and do not + necessarily span the full route. + + In the absence of a road stretch to style, the + client should apply the default for the route. + """ + + class RoadStretch(proto.Message): + r"""One road stretch that should be rendered. + + Attributes: + style (google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering.RoadStretch.Style): + Required. The style to apply. + offset_meters (int): + Required. The style should be applied between + ``[offset_meters, offset_meters + length_meters)``. + length_meters (int): + Required. The length of the path where to + apply the style. + """ + class Style(proto.Enum): + r"""The traffic style, indicating traffic speed. + + Values: + STYLE_UNSPECIFIED (0): + No style selected. + SLOWER_TRAFFIC (1): + Traffic is slowing down. + TRAFFIC_JAM (2): + There is a traffic jam. + """ + STYLE_UNSPECIFIED = 0 + SLOWER_TRAFFIC = 1 + TRAFFIC_JAM = 2 + + style: 'VisualTrafficReportPolylineRendering.RoadStretch.Style' = proto.Field( + proto.ENUM, + number=1, + enum='VisualTrafficReportPolylineRendering.RoadStretch.Style', + ) + offset_meters: int = proto.Field( + proto.INT32, + number=2, + ) + length_meters: int = proto.Field( + proto.INT32, + number=3, + ) + + road_stretch: MutableSequence[RoadStretch] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=RoadStretch, + ) + + +class TrafficPolylineData(proto.Message): + r"""Traffic conditions along the expected vehicle route. + + Attributes: + traffic_rendering (google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering): + A polyline rendering of how fast traffic is + for all regions along one stretch of a customer + ride. + """ + + traffic_rendering: 'VisualTrafficReportPolylineRendering' = proto.Field( + proto.MESSAGE, + number=1, + message='VisualTrafficReportPolylineRendering', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/mypy.ini b/owl-bot-staging/google-maps-fleetengine/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-maps-fleetengine/v1/noxfile.py b/owl-bot-staging/google-maps-fleetengine/v1/noxfile.py new file mode 100644 index 000000000000..4bc01f860119 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine' + +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/fleetengine_v1/', + '--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/fleetengine_v1/', + '--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-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py new file mode 100644 index 000000000000..ab45c932839a --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py @@ -0,0 +1,53 @@ +# -*- 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 CreateTrip +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_CreateTrip_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 fleetengine_v1 + + +async def sample_create_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateTripRequest( + parent="parent_value", + trip_id="trip_id_value", + ) + + # Make the request + response = await client.create_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_CreateTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py new file mode 100644 index 000000000000..c4644b1862d3 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py @@ -0,0 +1,53 @@ +# -*- 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 CreateTrip +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_CreateTrip_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 fleetengine_v1 + + +def sample_create_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateTripRequest( + parent="parent_value", + trip_id="trip_id_value", + ) + + # Make the request + response = client.create_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_CreateTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py new file mode 100644 index 000000000000..0c2d7cd52ca9 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_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 GetTrip +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_GetTrip_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 fleetengine_v1 + + +async def sample_get_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetTripRequest( + name="name_value", + ) + + # Make the request + response = await client.get_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_GetTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py new file mode 100644 index 000000000000..d3bfcfe709c0 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_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 GetTrip +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_GetTrip_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 fleetengine_v1 + + +def sample_get_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetTripRequest( + name="name_value", + ) + + # Make the request + response = client.get_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_GetTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py new file mode 100644 index 000000000000..8e32e9b6f3a9 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_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 ReportBillableTrip +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_ReportBillableTrip_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 fleetengine_v1 + + +async def sample_report_billable_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.ReportBillableTripRequest( + name="name_value", + country_code="country_code_value", + ) + + # Make the request + await client.report_billable_trip(request=request) + + +# [END fleetengine_v1_generated_TripService_ReportBillableTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py new file mode 100644 index 000000000000..0ea03be8d902 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_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 ReportBillableTrip +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_ReportBillableTrip_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 fleetengine_v1 + + +def sample_report_billable_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.ReportBillableTripRequest( + name="name_value", + country_code="country_code_value", + ) + + # Make the request + client.report_billable_trip(request=request) + + +# [END fleetengine_v1_generated_TripService_ReportBillableTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py new file mode 100644 index 000000000000..5cd30f613daa --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py @@ -0,0 +1,53 @@ +# -*- 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 SearchTrips +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_SearchTrips_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 fleetengine_v1 + + +async def sample_search_trips(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchTripsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.search_trips(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END fleetengine_v1_generated_TripService_SearchTrips_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py new file mode 100644 index 000000000000..dfbbfe500c95 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py @@ -0,0 +1,53 @@ +# -*- 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 SearchTrips +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_SearchTrips_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 fleetengine_v1 + + +def sample_search_trips(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchTripsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.search_trips(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END fleetengine_v1_generated_TripService_SearchTrips_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py new file mode 100644 index 000000000000..f67869a7143d --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_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 UpdateTrip +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_UpdateTrip_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 fleetengine_v1 + + +async def sample_update_trip(): + # Create a client + client = fleetengine_v1.TripServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateTripRequest( + name="name_value", + ) + + # Make the request + response = await client.update_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_UpdateTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py new file mode 100644 index 000000000000..fc41bd61a318 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_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 UpdateTrip +# 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-fleetengine + + +# [START fleetengine_v1_generated_TripService_UpdateTrip_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 fleetengine_v1 + + +def sample_update_trip(): + # Create a client + client = fleetengine_v1.TripServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateTripRequest( + name="name_value", + ) + + # Make the request + response = client.update_trip(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_TripService_UpdateTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py new file mode 100644 index 000000000000..851946fd95a3 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py @@ -0,0 +1,53 @@ +# -*- 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 CreateVehicle +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_CreateVehicle_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 fleetengine_v1 + + +async def sample_create_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateVehicleRequest( + parent="parent_value", + vehicle_id="vehicle_id_value", + ) + + # Make the request + response = await client.create_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_CreateVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py new file mode 100644 index 000000000000..24820678e5df --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py @@ -0,0 +1,53 @@ +# -*- 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 CreateVehicle +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_CreateVehicle_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 fleetengine_v1 + + +def sample_create_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.CreateVehicleRequest( + parent="parent_value", + vehicle_id="vehicle_id_value", + ) + + # Make the request + response = client.create_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_CreateVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py new file mode 100644 index 000000000000..39c32d3272f7 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_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 GetVehicle +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_GetVehicle_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 fleetengine_v1 + + +async def sample_get_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetVehicleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_GetVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py new file mode 100644 index 000000000000..3b852145ad23 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_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 GetVehicle +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_GetVehicle_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 fleetengine_v1 + + +def sample_get_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.GetVehicleRequest( + name="name_value", + ) + + # Make the request + response = client.get_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_GetVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py new file mode 100644 index 000000000000..969785d1f002 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py @@ -0,0 +1,54 @@ +# -*- 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 ListVehicles +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_ListVehicles_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 fleetengine_v1 + + +async def sample_list_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.ListVehiclesRequest( + parent="parent_value", + vehicle_type_categories=['PEDESTRIAN'], + ) + + # Make the request + page_result = client.list_vehicles(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END fleetengine_v1_generated_VehicleService_ListVehicles_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py new file mode 100644 index 000000000000..32329e16b91d --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py @@ -0,0 +1,54 @@ +# -*- 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 ListVehicles +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_ListVehicles_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 fleetengine_v1 + + +def sample_list_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.ListVehiclesRequest( + parent="parent_value", + vehicle_type_categories=['PEDESTRIAN'], + ) + + # Make the request + page_result = client.list_vehicles(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END fleetengine_v1_generated_VehicleService_ListVehicles_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py new file mode 100644 index 000000000000..72dbea4e2525 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchVehicles +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_SearchVehicles_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 fleetengine_v1 + + +async def sample_search_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchVehiclesRequest( + parent="parent_value", + pickup_radius_meters=2146, + count=553, + minimum_capacity=1705, + trip_types=['EXCLUSIVE'], + order_by="COST", + ) + + # Make the request + response = await client.search_vehicles(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_SearchVehicles_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py new file mode 100644 index 000000000000..9d2ea3d1cd7f --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchVehicles +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_SearchVehicles_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 fleetengine_v1 + + +def sample_search_vehicles(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.SearchVehiclesRequest( + parent="parent_value", + pickup_radius_meters=2146, + count=553, + minimum_capacity=1705, + trip_types=['EXCLUSIVE'], + order_by="COST", + ) + + # Make the request + response = client.search_vehicles(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_SearchVehicles_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py new file mode 100644 index 000000000000..83ef89e4566b --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_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 UpdateVehicle +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_UpdateVehicle_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 fleetengine_v1 + + +async def sample_update_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateVehicleRequest( + name="name_value", + ) + + # Make the request + response = await client.update_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_UpdateVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py new file mode 100644 index 000000000000..9b5d10d7db81 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateVehicleAttributes +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_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 fleetengine_v1 + + +async def sample_update_vehicle_attributes(): + # Create a client + client = fleetengine_v1.VehicleServiceAsyncClient() + + # Initialize request argument(s) + attributes = fleetengine_v1.VehicleAttribute() + attributes.string_value = "string_value_value" + + request = fleetengine_v1.UpdateVehicleAttributesRequest( + name="name_value", + attributes=attributes, + ) + + # Make the request + response = await client.update_vehicle_attributes(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py new file mode 100644 index 000000000000..ae0d5f325998 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateVehicleAttributes +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_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 fleetengine_v1 + + +def sample_update_vehicle_attributes(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + attributes = fleetengine_v1.VehicleAttribute() + attributes.string_value = "string_value_value" + + request = fleetengine_v1.UpdateVehicleAttributesRequest( + name="name_value", + attributes=attributes, + ) + + # Make the request + response = client.update_vehicle_attributes(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py new file mode 100644 index 000000000000..f1ae021b0f99 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_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 UpdateVehicle +# 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-fleetengine + + +# [START fleetengine_v1_generated_VehicleService_UpdateVehicle_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 fleetengine_v1 + + +def sample_update_vehicle(): + # Create a client + client = fleetengine_v1.VehicleServiceClient() + + # Initialize request argument(s) + request = fleetengine_v1.UpdateVehicleRequest( + name="name_value", + ) + + # Make the request + response = client.update_vehicle(request=request) + + # Handle the response + print(response) + +# [END fleetengine_v1_generated_VehicleService_UpdateVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json new file mode 100644 index 000000000000..b0139d358773 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json @@ -0,0 +1,1692 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "maps.fleetengine.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-maps-fleetengine", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", + "shortName": "TripServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.create_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.CreateTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "CreateTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.CreateTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "create_trip" + }, + "description": "Sample for CreateTrip", + "file": "fleetengine_v1_generated_trip_service_create_trip_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_CreateTrip_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_create_trip_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceClient", + "shortName": "TripServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceClient.create_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.CreateTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "CreateTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.CreateTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "create_trip" + }, + "description": "Sample for CreateTrip", + "file": "fleetengine_v1_generated_trip_service_create_trip_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_CreateTrip_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_create_trip_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", + "shortName": "TripServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.get_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.GetTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "GetTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.GetTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "get_trip" + }, + "description": "Sample for GetTrip", + "file": "fleetengine_v1_generated_trip_service_get_trip_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_GetTrip_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_get_trip_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceClient", + "shortName": "TripServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceClient.get_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.GetTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "GetTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.GetTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "get_trip" + }, + "description": "Sample for GetTrip", + "file": "fleetengine_v1_generated_trip_service_get_trip_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_GetTrip_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_get_trip_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", + "shortName": "TripServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.report_billable_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.ReportBillableTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "ReportBillableTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.ReportBillableTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "report_billable_trip" + }, + "description": "Sample for ReportBillableTrip", + "file": "fleetengine_v1_generated_trip_service_report_billable_trip_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_ReportBillableTrip_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_report_billable_trip_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceClient", + "shortName": "TripServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceClient.report_billable_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.ReportBillableTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "ReportBillableTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.ReportBillableTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "report_billable_trip" + }, + "description": "Sample for ReportBillableTrip", + "file": "fleetengine_v1_generated_trip_service_report_billable_trip_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_ReportBillableTrip_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_report_billable_trip_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", + "shortName": "TripServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.search_trips", + "method": { + "fullName": "maps.fleetengine.v1.TripService.SearchTrips", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "SearchTrips" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.SearchTripsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsAsyncPager", + "shortName": "search_trips" + }, + "description": "Sample for SearchTrips", + "file": "fleetengine_v1_generated_trip_service_search_trips_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_SearchTrips_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_search_trips_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceClient", + "shortName": "TripServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceClient.search_trips", + "method": { + "fullName": "maps.fleetengine.v1.TripService.SearchTrips", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "SearchTrips" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.SearchTripsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsPager", + "shortName": "search_trips" + }, + "description": "Sample for SearchTrips", + "file": "fleetengine_v1_generated_trip_service_search_trips_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_SearchTrips_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_search_trips_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", + "shortName": "TripServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.update_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.UpdateTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "UpdateTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "update_trip" + }, + "description": "Sample for UpdateTrip", + "file": "fleetengine_v1_generated_trip_service_update_trip_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_UpdateTrip_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_update_trip_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.TripServiceClient", + "shortName": "TripServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.TripServiceClient.update_trip", + "method": { + "fullName": "maps.fleetengine.v1.TripService.UpdateTrip", + "service": { + "fullName": "maps.fleetengine.v1.TripService", + "shortName": "TripService" + }, + "shortName": "UpdateTrip" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateTripRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Trip", + "shortName": "update_trip" + }, + "description": "Sample for UpdateTrip", + "file": "fleetengine_v1_generated_trip_service_update_trip_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_TripService_UpdateTrip_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_trip_service_update_trip_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.create_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.CreateVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "CreateVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.CreateVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "create_vehicle" + }, + "description": "Sample for CreateVehicle", + "file": "fleetengine_v1_generated_vehicle_service_create_vehicle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_CreateVehicle_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_create_vehicle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.create_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.CreateVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "CreateVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.CreateVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "create_vehicle" + }, + "description": "Sample for CreateVehicle", + "file": "fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_CreateVehicle_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.get_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.GetVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "GetVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.GetVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "get_vehicle" + }, + "description": "Sample for GetVehicle", + "file": "fleetengine_v1_generated_vehicle_service_get_vehicle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_GetVehicle_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_get_vehicle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.get_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.GetVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "GetVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.GetVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "get_vehicle" + }, + "description": "Sample for GetVehicle", + "file": "fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_GetVehicle_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.list_vehicles", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.ListVehicles", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "ListVehicles" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.ListVehiclesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesAsyncPager", + "shortName": "list_vehicles" + }, + "description": "Sample for ListVehicles", + "file": "fleetengine_v1_generated_vehicle_service_list_vehicles_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_ListVehicles_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_list_vehicles_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.list_vehicles", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.ListVehicles", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "ListVehicles" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.ListVehiclesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesPager", + "shortName": "list_vehicles" + }, + "description": "Sample for ListVehicles", + "file": "fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_ListVehicles_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.search_vehicles", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.SearchVehicles", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "SearchVehicles" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.SearchVehiclesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.SearchVehiclesResponse", + "shortName": "search_vehicles" + }, + "description": "Sample for SearchVehicles", + "file": "fleetengine_v1_generated_vehicle_service_search_vehicles_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_SearchVehicles_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_search_vehicles_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.search_vehicles", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.SearchVehicles", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "SearchVehicles" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.SearchVehiclesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.SearchVehiclesResponse", + "shortName": "search_vehicles" + }, + "description": "Sample for SearchVehicles", + "file": "fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_SearchVehicles_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.update_vehicle_attributes", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicleAttributes", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "UpdateVehicleAttributes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse", + "shortName": "update_vehicle_attributes" + }, + "description": "Sample for UpdateVehicleAttributes", + "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.update_vehicle_attributes", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicleAttributes", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "UpdateVehicleAttributes" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse", + "shortName": "update_vehicle_attributes" + }, + "description": "Sample for UpdateVehicleAttributes", + "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", + "shortName": "VehicleServiceAsyncClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.update_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "UpdateVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "update_vehicle" + }, + "description": "Sample for UpdateVehicle", + "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicle_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_update_vehicle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", + "shortName": "VehicleServiceClient" + }, + "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.update_vehicle", + "method": { + "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicle", + "service": { + "fullName": "maps.fleetengine.v1.VehicleService", + "shortName": "VehicleService" + }, + "shortName": "UpdateVehicle" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.fleetengine_v1.types.UpdateVehicleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.fleetengine_v1.types.Vehicle", + "shortName": "update_vehicle" + }, + "description": "Sample for UpdateVehicle", + "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicle_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py b/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py new file mode 100644 index 000000000000..1a4c9837d26c --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py @@ -0,0 +1,186 @@ +#! /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 fleetengineCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_trip': ('parent', 'trip_id', 'trip', 'header', ), + 'create_vehicle': ('parent', 'vehicle_id', 'vehicle', 'header', ), + 'get_trip': ('name', 'header', 'view', 'current_route_segment_version', 'remaining_waypoints_version', 'route_format_type', 'current_route_segment_traffic_version', 'remaining_waypoints_route_version', ), + 'get_vehicle': ('name', 'header', 'current_route_segment_version', 'waypoints_version', ), + 'list_vehicles': ('parent', 'vehicle_type_categories', 'header', 'page_size', 'page_token', 'minimum_capacity', 'trip_types', 'maximum_staleness', 'required_attributes', 'required_one_of_attributes', 'required_one_of_attribute_sets', 'vehicle_state', 'on_trip_only', 'filter', 'viewport', ), + 'report_billable_trip': ('name', 'country_code', 'platform', 'related_ids', 'solution_type', ), + 'search_trips': ('parent', 'header', 'vehicle_id', 'active_trips_only', 'page_size', 'page_token', 'minimum_staleness', ), + 'search_vehicles': ('parent', 'pickup_point', 'pickup_radius_meters', 'count', 'minimum_capacity', 'trip_types', 'vehicle_types', 'order_by', 'header', 'dropoff_point', 'maximum_staleness', 'required_attributes', 'required_one_of_attributes', 'required_one_of_attribute_sets', 'include_back_to_back', 'trip_id', 'current_trips_present', 'filter', ), + 'update_trip': ('name', 'trip', 'update_mask', 'header', ), + 'update_vehicle': ('name', 'vehicle', 'update_mask', 'header', ), + 'update_vehicle_attributes': ('name', 'attributes', 'header', ), + } + + 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=fleetengineCallTransformer(), +): + """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 fleetengine 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-fleetengine/v1/setup.py b/owl-bot-staging/google-maps-fleetengine/v1/setup.py new file mode 100644 index 000000000000..b805ff698554 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine' + + +description = "Google Maps Fleetengine API client library" + +version = None + +with open(os.path.join(package_root, 'google/maps/fleetengine/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-fleetengine" + +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-fleetengine/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..277853c664a0 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..2214a366a259 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/tests/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__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-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py new file mode 100644 index 000000000000..bb902fed5d70 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py @@ -0,0 +1,3025 @@ +# -*- 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 +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 + +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.fleetengine_v1.services.trip_service import TripServiceAsyncClient +from google.maps.fleetengine_v1.services.trip_service import TripServiceClient +from google.maps.fleetengine_v1.services.trip_service import pagers +from google.maps.fleetengine_v1.services.trip_service import transports +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import header +from google.maps.fleetengine_v1.types import traffic +from google.maps.fleetengine_v1.types import trip_api +from google.maps.fleetengine_v1.types import trips +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_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 TripServiceClient._get_default_mtls_endpoint(None) is None + assert TripServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TripServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TripServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TripServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TripServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert TripServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert TripServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert TripServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + TripServiceClient._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 TripServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert TripServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert TripServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + TripServiceClient._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 TripServiceClient._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 TripServiceClient._get_client_cert_source(None, False) is None + assert TripServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert TripServiceClient._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 TripServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert TripServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) +@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = TripServiceClient._DEFAULT_UNIVERSE + default_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert TripServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert TripServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TripServiceClient.DEFAULT_MTLS_ENDPOINT + assert TripServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert TripServiceClient._get_api_endpoint(None, None, default_universe, "always") == TripServiceClient.DEFAULT_MTLS_ENDPOINT + assert TripServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TripServiceClient.DEFAULT_MTLS_ENDPOINT + assert TripServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert TripServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + TripServiceClient._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 TripServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert TripServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert TripServiceClient._get_universe_domain(None, None) == TripServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + TripServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (TripServiceClient, "grpc"), + (TripServiceAsyncClient, "grpc_asyncio"), +]) +def test_trip_service_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 == ( + 'fleetengine.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.TripServiceGrpcTransport, "grpc"), + (transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_trip_service_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", [ + (TripServiceClient, "grpc"), + (TripServiceAsyncClient, "grpc_asyncio"), +]) +def test_trip_service_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 == ( + 'fleetengine.googleapis.com:443' + ) + + +def test_trip_service_client_get_transport_class(): + transport = TripServiceClient.get_transport_class() + available_transports = [ + transports.TripServiceGrpcTransport, + ] + assert transport in available_transports + + transport = TripServiceClient.get_transport_class("grpc") + assert transport == transports.TripServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc"), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) +@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) +def test_trip_service_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(TripServiceClient, '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(TripServiceClient, '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", [ + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", "true"), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", "false"), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) +@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_trip_service_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", [ + TripServiceClient, TripServiceAsyncClient +]) +@mock.patch.object(TripServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TripServiceClient)) +@mock.patch.object(TripServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TripServiceAsyncClient)) +def test_trip_service_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", [ + TripServiceClient, TripServiceAsyncClient +]) +@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) +@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) +def test_trip_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = TripServiceClient._DEFAULT_UNIVERSE + default_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TripServiceClient._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", [ + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc"), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_trip_service_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", [ + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", grpc_helpers), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_trip_service_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_trip_service_client_client_options_from_dict(): + with mock.patch('google.maps.fleetengine_v1.services.trip_service.transports.TripServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TripServiceClient( + 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", [ + (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", grpc_helpers), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_trip_service_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( + "fleetengine.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="fleetengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + trip_api.CreateTripRequest, + dict, +]) +def test_create_trip(request_type, transport: str = 'grpc'): + client = TripServiceClient( + 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.create_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + ) + response = client.create_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = trip_api.CreateTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +def test_create_trip_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 = TripServiceClient( + 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 = trip_api.CreateTripRequest( + parent='parent_value', + trip_id='trip_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_trip), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_trip(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == trip_api.CreateTripRequest( + parent='parent_value', + trip_id='trip_id_value', + ) + +def test_create_trip_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 = TripServiceClient( + 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.create_trip 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.create_trip] = mock_rpc + request = {} + client.create_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_trip(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_create_trip_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 = TripServiceAsyncClient( + 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.create_trip 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.create_trip] = mock_rpc + + request = {} + await client.create_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_trip(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_create_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.CreateTripRequest): + client = TripServiceAsyncClient( + 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.create_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + response = await client.create_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = trip_api.CreateTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +@pytest.mark.asyncio +async def test_create_trip_async_from_dict(): + await test_create_trip_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + trip_api.GetTripRequest, + dict, +]) +def test_get_trip(request_type, transport: str = 'grpc'): + client = TripServiceClient( + 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.get_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + ) + response = client.get_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = trip_api.GetTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +def test_get_trip_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 = TripServiceClient( + 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 = trip_api.GetTripRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_trip), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_trip(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == trip_api.GetTripRequest( + name='name_value', + ) + +def test_get_trip_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 = TripServiceClient( + 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.get_trip 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.get_trip] = mock_rpc + request = {} + client.get_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_trip(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_get_trip_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 = TripServiceAsyncClient( + 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.get_trip 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.get_trip] = mock_rpc + + request = {} + await client.get_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_trip(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_get_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.GetTripRequest): + client = TripServiceAsyncClient( + 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.get_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + response = await client.get_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = trip_api.GetTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +@pytest.mark.asyncio +async def test_get_trip_async_from_dict(): + await test_get_trip_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + trip_api.ReportBillableTripRequest, + dict, +]) +def test_report_billable_trip(request_type, transport: str = 'grpc'): + client = TripServiceClient( + 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.report_billable_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.report_billable_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = trip_api.ReportBillableTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_report_billable_trip_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 = TripServiceClient( + 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 = trip_api.ReportBillableTripRequest( + name='name_value', + country_code='country_code_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.report_billable_trip(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == trip_api.ReportBillableTripRequest( + name='name_value', + country_code='country_code_value', + ) + +def test_report_billable_trip_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 = TripServiceClient( + 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.report_billable_trip 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.report_billable_trip] = mock_rpc + request = {} + client.report_billable_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.report_billable_trip(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_report_billable_trip_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 = TripServiceAsyncClient( + 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.report_billable_trip 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.report_billable_trip] = mock_rpc + + request = {} + await client.report_billable_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.report_billable_trip(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_report_billable_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.ReportBillableTripRequest): + client = TripServiceAsyncClient( + 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.report_billable_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.report_billable_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = trip_api.ReportBillableTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_report_billable_trip_async_from_dict(): + await test_report_billable_trip_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + trip_api.SearchTripsRequest, + dict, +]) +def test_search_trips(request_type, transport: str = 'grpc'): + client = TripServiceClient( + 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.search_trips), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = trip_api.SearchTripsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_trips(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = trip_api.SearchTripsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchTripsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_trips_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 = TripServiceClient( + 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 = trip_api.SearchTripsRequest( + parent='parent_value', + vehicle_id='vehicle_id_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_trips(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == trip_api.SearchTripsRequest( + parent='parent_value', + vehicle_id='vehicle_id_value', + page_token='page_token_value', + ) + +def test_search_trips_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 = TripServiceClient( + 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.search_trips 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.search_trips] = mock_rpc + request = {} + client.search_trips(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_trips(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_search_trips_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 = TripServiceAsyncClient( + 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.search_trips 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.search_trips] = mock_rpc + + request = {} + await client.search_trips(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.search_trips(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_search_trips_async(transport: str = 'grpc_asyncio', request_type=trip_api.SearchTripsRequest): + client = TripServiceAsyncClient( + 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.search_trips), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_trips(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = trip_api.SearchTripsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchTripsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_trips_async_from_dict(): + await test_search_trips_async(request_type=dict) + + +def test_search_trips_pager(transport_name: str = "grpc"): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + trips.Trip(), + ], + next_page_token='abc', + ), + trip_api.SearchTripsResponse( + trips=[], + next_page_token='def', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + ], + next_page_token='ghi', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.search_trips(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, trips.Trip) + for i in results) +def test_search_trips_pages(transport_name: str = "grpc"): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + trips.Trip(), + ], + next_page_token='abc', + ), + trip_api.SearchTripsResponse( + trips=[], + next_page_token='def', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + ], + next_page_token='ghi', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + ], + ), + RuntimeError, + ) + pages = list(client.search_trips(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_trips_async_pager(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + trips.Trip(), + ], + next_page_token='abc', + ), + trip_api.SearchTripsResponse( + trips=[], + next_page_token='def', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + ], + next_page_token='ghi', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_trips(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, trips.Trip) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_trips_async_pages(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + trips.Trip(), + ], + next_page_token='abc', + ), + trip_api.SearchTripsResponse( + trips=[], + next_page_token='def', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + ], + next_page_token='ghi', + ), + trip_api.SearchTripsResponse( + trips=[ + trips.Trip(), + trips.Trip(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search_trips(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + trip_api.UpdateTripRequest, + dict, +]) +def test_update_trip(request_type, transport: str = 'grpc'): + client = TripServiceClient( + 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.update_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + ) + response = client.update_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = trip_api.UpdateTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +def test_update_trip_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 = TripServiceClient( + 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 = trip_api.UpdateTripRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_trip), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_trip(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == trip_api.UpdateTripRequest( + name='name_value', + ) + +def test_update_trip_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 = TripServiceClient( + 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.update_trip 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.update_trip] = mock_rpc + request = {} + client.update_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_trip(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_update_trip_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 = TripServiceAsyncClient( + 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.update_trip 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.update_trip] = mock_rpc + + request = {} + await client.update_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_trip(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_update_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.UpdateTripRequest): + client = TripServiceAsyncClient( + 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.update_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + response = await client.update_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = trip_api.UpdateTripRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, trips.Trip) + assert response.name == 'name_value' + assert response.vehicle_id == 'vehicle_id_value' + assert response.trip_status == trips.TripStatus.NEW + assert response.trip_type == fleetengine.TripType.SHARED + assert response.intermediate_destination_index == 3187 + assert response.current_route_segment == 'current_route_segment_value' + assert response.number_of_passengers == 2135 + assert response.last_location_snappable is True + assert response.view == trips.TripView.SDK + + +@pytest.mark.asyncio +async def test_update_trip_async_from_dict(): + await test_update_trip_async(request_type=dict) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TripServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TripServiceClient( + 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 = TripServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TripServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TripServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TripServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TripServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TripServiceGrpcTransport, + transports.TripServiceGrpcAsyncIOTransport, +]) +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 = TripServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = TripServiceClient( + 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_create_trip_empty_call_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.create_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.CreateTripRequest() + + 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_get_trip_empty_call_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.get_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.GetTripRequest() + + 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_report_billable_trip_empty_call_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + call.return_value = None + client.report_billable_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.ReportBillableTripRequest() + + 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_search_trips_empty_call_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__') as call: + call.return_value = trip_api.SearchTripsResponse() + client.search_trips(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.SearchTripsRequest() + + 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_update_trip_empty_call_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.update_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.UpdateTripRequest() + + assert args[0] == request_msg + + +def test_create_trip_routing_parameters_request_1_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.create_trip(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.CreateTripRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_get_trip_routing_parameters_request_1_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.get_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.GetTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_report_billable_trip_routing_parameters_request_1_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + call.return_value = None + client.report_billable_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.ReportBillableTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_search_trips_routing_parameters_request_1_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__') as call: + call.return_value = trip_api.SearchTripsResponse() + client.search_trips(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.SearchTripsRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_update_trip_routing_parameters_request_1_grpc(): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_trip), + '__call__') as call: + call.return_value = trips.Trip() + client.update_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.UpdateTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_kind_grpc_asyncio(): + transport = TripServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = TripServiceAsyncClient( + 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_create_trip_empty_call_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.create_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.CreateTripRequest() + + 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_get_trip_empty_call_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.get_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.GetTripRequest() + + 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_report_billable_trip_empty_call_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.report_billable_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.ReportBillableTripRequest() + + 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_search_trips_empty_call_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( + next_page_token='next_page_token_value', + )) + await client.search_trips(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.SearchTripsRequest() + + 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_update_trip_empty_call_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.update_trip(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = trip_api.UpdateTripRequest() + + assert args[0] == request_msg + + +@pytest.mark.asyncio +async def test_create_trip_routing_parameters_request_1_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.create_trip(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.CreateTripRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_get_trip_routing_parameters_request_1_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.get_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.GetTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_report_billable_trip_routing_parameters_request_1_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_billable_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.report_billable_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.ReportBillableTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_search_trips_routing_parameters_request_1_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_trips), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( + next_page_token='next_page_token_value', + )) + await client.search_trips(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.SearchTripsRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_update_trip_routing_parameters_request_1_grpc_asyncio(): + client = TripServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_trip), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( + name='name_value', + vehicle_id='vehicle_id_value', + trip_status=trips.TripStatus.NEW, + trip_type=fleetengine.TripType.SHARED, + intermediate_destination_index=3187, + current_route_segment='current_route_segment_value', + number_of_passengers=2135, + last_location_snappable=True, + view=trips.TripView.SDK, + )) + await client.update_trip(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = trip_api.UpdateTripRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TripServiceGrpcTransport, + ) + +def test_trip_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TripServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_trip_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.fleetengine_v1.services.trip_service.transports.TripServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TripServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_trip', + 'get_trip', + 'report_billable_trip', + 'search_trips', + 'update_trip', + ) + 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_trip_service_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.fleetengine_v1.services.trip_service.transports.TripServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TripServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_trip_service_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.fleetengine_v1.services.trip_service.transports.TripServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TripServiceTransport() + adc.assert_called_once() + + +def test_trip_service_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) + TripServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TripServiceGrpcTransport, + transports.TripServiceGrpcAsyncIOTransport, + ], +) +def test_trip_service_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=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TripServiceGrpcTransport, + transports.TripServiceGrpcAsyncIOTransport, + ], +) +def test_trip_service_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.TripServiceGrpcTransport, grpc_helpers), + (transports.TripServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_trip_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "fleetengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="fleetengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) +def test_trip_service_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_trip_service_host_no_port(transport_name): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'fleetengine.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_trip_service_host_with_port(transport_name): + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'fleetengine.googleapis.com:8000' + ) + +def test_trip_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TripServiceGrpcTransport( + 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_trip_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TripServiceGrpcAsyncIOTransport( + 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.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) +def test_trip_service_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.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) +def test_trip_service_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_trip_path(): + provider = "squid" + trip = "clam" + expected = "providers/{provider}/trips/{trip}".format(provider=provider, trip=trip, ) + actual = TripServiceClient.trip_path(provider, trip) + assert expected == actual + + +def test_parse_trip_path(): + expected = { + "provider": "whelk", + "trip": "octopus", + } + path = TripServiceClient.trip_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.parse_trip_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TripServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = TripServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = TripServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = TripServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TripServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = TripServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = TripServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = TripServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = TripServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = TripServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TripServiceClient.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.TripServiceTransport, '_prep_wrapped_messages') as prep: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TripServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = TripServiceClient.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 = TripServiceClient( + 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 = TripServiceAsyncClient( + 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_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = TripServiceClient( + 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", [ + (TripServiceClient, transports.TripServiceGrpcTransport), + (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport), +]) +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/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py new file mode 100644 index 000000000000..9853af860e76 --- /dev/null +++ b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py @@ -0,0 +1,3280 @@ +# -*- 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 +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 + +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.geo.type.types import viewport +from google.maps.fleetengine_v1.services.vehicle_service import VehicleServiceAsyncClient +from google.maps.fleetengine_v1.services.vehicle_service import VehicleServiceClient +from google.maps.fleetengine_v1.services.vehicle_service import pagers +from google.maps.fleetengine_v1.services.vehicle_service import transports +from google.maps.fleetengine_v1.types import fleetengine +from google.maps.fleetengine_v1.types import header +from google.maps.fleetengine_v1.types import traffic +from google.maps.fleetengine_v1.types import vehicle_api +from google.maps.fleetengine_v1.types import vehicles +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_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 VehicleServiceClient._get_default_mtls_endpoint(None) is None + assert VehicleServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert VehicleServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert VehicleServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert VehicleServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert VehicleServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert VehicleServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + VehicleServiceClient._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 VehicleServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert VehicleServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + VehicleServiceClient._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 VehicleServiceClient._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 VehicleServiceClient._get_client_cert_source(None, False) is None + assert VehicleServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert VehicleServiceClient._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 VehicleServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert VehicleServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) +@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = VehicleServiceClient._DEFAULT_UNIVERSE + default_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert VehicleServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert VehicleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT + assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "always") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT + assert VehicleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT + assert VehicleServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + VehicleServiceClient._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 VehicleServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert VehicleServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert VehicleServiceClient._get_universe_domain(None, None) == VehicleServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + VehicleServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (VehicleServiceClient, "grpc"), + (VehicleServiceAsyncClient, "grpc_asyncio"), +]) +def test_vehicle_service_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 == ( + 'fleetengine.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.VehicleServiceGrpcTransport, "grpc"), + (transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_vehicle_service_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", [ + (VehicleServiceClient, "grpc"), + (VehicleServiceAsyncClient, "grpc_asyncio"), +]) +def test_vehicle_service_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 == ( + 'fleetengine.googleapis.com:443' + ) + + +def test_vehicle_service_client_get_transport_class(): + transport = VehicleServiceClient.get_transport_class() + available_transports = [ + transports.VehicleServiceGrpcTransport, + ] + assert transport in available_transports + + transport = VehicleServiceClient.get_transport_class("grpc") + assert transport == transports.VehicleServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc"), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) +@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) +def test_vehicle_service_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(VehicleServiceClient, '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(VehicleServiceClient, '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", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", "true"), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", "false"), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) +@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_vehicle_service_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", [ + VehicleServiceClient, VehicleServiceAsyncClient +]) +@mock.patch.object(VehicleServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VehicleServiceClient)) +@mock.patch.object(VehicleServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VehicleServiceAsyncClient)) +def test_vehicle_service_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", [ + VehicleServiceClient, VehicleServiceAsyncClient +]) +@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) +@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) +def test_vehicle_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = VehicleServiceClient._DEFAULT_UNIVERSE + default_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = VehicleServiceClient._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", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc"), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_vehicle_service_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", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", grpc_helpers), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_vehicle_service_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_vehicle_service_client_client_options_from_dict(): + with mock.patch('google.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = VehicleServiceClient( + 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", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", grpc_helpers), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_vehicle_service_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( + "fleetengine.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="fleetengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + vehicle_api.CreateVehicleRequest, + dict, +]) +def test_create_vehicle(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + 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.create_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + ) + response = client.create_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.CreateVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +def test_create_vehicle_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 = VehicleServiceClient( + 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 = vehicle_api.CreateVehicleRequest( + parent='parent_value', + vehicle_id='vehicle_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_vehicle), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_vehicle(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.CreateVehicleRequest( + parent='parent_value', + vehicle_id='vehicle_id_value', + ) + +def test_create_vehicle_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 = VehicleServiceClient( + 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.create_vehicle 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.create_vehicle] = mock_rpc + request = {} + client.create_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_vehicle(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_create_vehicle_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 = VehicleServiceAsyncClient( + 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.create_vehicle 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.create_vehicle] = mock_rpc + + request = {} + await client.create_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_vehicle(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_create_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.CreateVehicleRequest): + client = VehicleServiceAsyncClient( + 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.create_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + response = await client.create_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.CreateVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +@pytest.mark.asyncio +async def test_create_vehicle_async_from_dict(): + await test_create_vehicle_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + vehicle_api.GetVehicleRequest, + dict, +]) +def test_get_vehicle(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + 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.get_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + ) + response = client.get_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.GetVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +def test_get_vehicle_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 = VehicleServiceClient( + 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 = vehicle_api.GetVehicleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vehicle), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_vehicle(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.GetVehicleRequest( + name='name_value', + ) + +def test_get_vehicle_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 = VehicleServiceClient( + 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.get_vehicle 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.get_vehicle] = mock_rpc + request = {} + client.get_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_vehicle(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_get_vehicle_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 = VehicleServiceAsyncClient( + 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.get_vehicle 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.get_vehicle] = mock_rpc + + request = {} + await client.get_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_vehicle(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_get_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.GetVehicleRequest): + client = VehicleServiceAsyncClient( + 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.get_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + response = await client.get_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.GetVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +@pytest.mark.asyncio +async def test_get_vehicle_async_from_dict(): + await test_get_vehicle_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + vehicle_api.UpdateVehicleRequest, + dict, +]) +def test_update_vehicle(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + 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.update_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + ) + response = client.update_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.UpdateVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +def test_update_vehicle_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 = VehicleServiceClient( + 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 = vehicle_api.UpdateVehicleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_vehicle(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.UpdateVehicleRequest( + name='name_value', + ) + +def test_update_vehicle_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 = VehicleServiceClient( + 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.update_vehicle 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.update_vehicle] = mock_rpc + request = {} + client.update_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_vehicle(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_update_vehicle_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 = VehicleServiceAsyncClient( + 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.update_vehicle 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.update_vehicle] = mock_rpc + + request = {} + await client.update_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_vehicle(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_update_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.UpdateVehicleRequest): + client = VehicleServiceAsyncClient( + 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.update_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + response = await client.update_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.UpdateVehicleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicles.Vehicle) + assert response.name == 'name_value' + assert response.vehicle_state == vehicles.VehicleState.OFFLINE + assert response.supported_trip_types == [fleetengine.TripType.SHARED] + assert response.current_trips == ['current_trips_value'] + assert response.maximum_capacity == 1707 + assert response.current_route_segment == 'current_route_segment_value' + assert response.back_to_back_enabled is True + assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE + + +@pytest.mark.asyncio +async def test_update_vehicle_async_from_dict(): + await test_update_vehicle_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + vehicle_api.UpdateVehicleAttributesRequest, + dict, +]) +def test_update_vehicle_attributes(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + 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.update_vehicle_attributes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicle_api.UpdateVehicleAttributesResponse( + ) + response = client.update_vehicle_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.UpdateVehicleAttributesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicle_api.UpdateVehicleAttributesResponse) + + +def test_update_vehicle_attributes_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 = VehicleServiceClient( + 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 = vehicle_api.UpdateVehicleAttributesRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle_attributes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_vehicle_attributes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.UpdateVehicleAttributesRequest( + name='name_value', + ) + +def test_update_vehicle_attributes_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 = VehicleServiceClient( + 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.update_vehicle_attributes 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.update_vehicle_attributes] = mock_rpc + request = {} + client.update_vehicle_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_vehicle_attributes(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_update_vehicle_attributes_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 = VehicleServiceAsyncClient( + 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.update_vehicle_attributes 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.update_vehicle_attributes] = mock_rpc + + request = {} + await client.update_vehicle_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_vehicle_attributes(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_update_vehicle_attributes_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.UpdateVehicleAttributesRequest): + client = VehicleServiceAsyncClient( + 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.update_vehicle_attributes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( + )) + response = await client.update_vehicle_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.UpdateVehicleAttributesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicle_api.UpdateVehicleAttributesResponse) + + +@pytest.mark.asyncio +async def test_update_vehicle_attributes_async_from_dict(): + await test_update_vehicle_attributes_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + vehicle_api.ListVehiclesRequest, + dict, +]) +def test_list_vehicles(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + 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.list_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicle_api.ListVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.ListVehiclesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVehiclesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_vehicles_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 = VehicleServiceClient( + 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 = vehicle_api.ListVehiclesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_vehicles(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.ListVehiclesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_vehicles_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 = VehicleServiceClient( + 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.list_vehicles 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.list_vehicles] = mock_rpc + request = {} + client.list_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_vehicles(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_list_vehicles_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 = VehicleServiceAsyncClient( + 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.list_vehicles 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.list_vehicles] = mock_rpc + + request = {} + await client.list_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_vehicles(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_list_vehicles_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.ListVehiclesRequest): + client = VehicleServiceAsyncClient( + 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.list_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.ListVehiclesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVehiclesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_vehicles_async_from_dict(): + await test_list_vehicles_async(request_type=dict) + + +def test_list_vehicles_pager(transport_name: str = "grpc"): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + next_page_token='abc', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[], + next_page_token='def', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + ], + next_page_token='ghi', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_vehicles(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, vehicles.Vehicle) + for i in results) +def test_list_vehicles_pages(transport_name: str = "grpc"): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + next_page_token='abc', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[], + next_page_token='def', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + ], + next_page_token='ghi', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + ), + RuntimeError, + ) + pages = list(client.list_vehicles(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_vehicles_async_pager(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + next_page_token='abc', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[], + next_page_token='def', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + ], + next_page_token='ghi', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_vehicles(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, vehicles.Vehicle) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_vehicles_async_pages(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + next_page_token='abc', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[], + next_page_token='def', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + ], + next_page_token='ghi', + ), + vehicle_api.ListVehiclesResponse( + vehicles=[ + vehicles.Vehicle(), + vehicles.Vehicle(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_vehicles(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + vehicle_api.SearchVehiclesRequest, + dict, +]) +def test_search_vehicles(request_type, transport: str = 'grpc'): + client = VehicleServiceClient( + 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.search_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = vehicle_api.SearchVehiclesResponse( + ) + response = client.search_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = vehicle_api.SearchVehiclesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicle_api.SearchVehiclesResponse) + + +def test_search_vehicles_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 = VehicleServiceClient( + 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 = vehicle_api.SearchVehiclesRequest( + parent='parent_value', + trip_id='trip_id_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_vehicles), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_vehicles(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vehicle_api.SearchVehiclesRequest( + parent='parent_value', + trip_id='trip_id_value', + filter='filter_value', + ) + +def test_search_vehicles_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 = VehicleServiceClient( + 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.search_vehicles 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.search_vehicles] = mock_rpc + request = {} + client.search_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_vehicles(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_search_vehicles_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 = VehicleServiceAsyncClient( + 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.search_vehicles 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.search_vehicles] = mock_rpc + + request = {} + await client.search_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.search_vehicles(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_search_vehicles_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.SearchVehiclesRequest): + client = VehicleServiceAsyncClient( + 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.search_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( + )) + response = await client.search_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = vehicle_api.SearchVehiclesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, vehicle_api.SearchVehiclesResponse) + + +@pytest.mark.asyncio +async def test_search_vehicles_async_from_dict(): + await test_search_vehicles_async(request_type=dict) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VehicleServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = VehicleServiceClient( + 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 = VehicleServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VehicleServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VehicleServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VehicleServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VehicleServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.VehicleServiceGrpcTransport, + transports.VehicleServiceGrpcAsyncIOTransport, +]) +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 = VehicleServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = VehicleServiceClient( + 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_create_vehicle_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.create_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.CreateVehicleRequest() + + 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_get_vehicle_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.get_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.GetVehicleRequest() + + 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_update_vehicle_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.update_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleRequest() + + 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_update_vehicle_attributes_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle_attributes), + '__call__') as call: + call.return_value = vehicle_api.UpdateVehicleAttributesResponse() + client.update_vehicle_attributes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleAttributesRequest() + + 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_list_vehicles_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + call.return_value = vehicle_api.ListVehiclesResponse() + client.list_vehicles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.ListVehiclesRequest() + + 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_search_vehicles_empty_call_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_vehicles), + '__call__') as call: + call.return_value = vehicle_api.SearchVehiclesResponse() + client.search_vehicles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.SearchVehiclesRequest() + + assert args[0] == request_msg + + +def test_create_vehicle_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.create_vehicle(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.CreateVehicleRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_get_vehicle_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.get_vehicle(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.GetVehicleRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_update_vehicle_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle), + '__call__') as call: + call.return_value = vehicles.Vehicle() + client.update_vehicle(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_update_vehicle_attributes_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle_attributes), + '__call__') as call: + call.return_value = vehicle_api.UpdateVehicleAttributesResponse() + client.update_vehicle_attributes(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleAttributesRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_list_vehicles_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + call.return_value = vehicle_api.ListVehiclesResponse() + client.list_vehicles(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.ListVehiclesRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +def test_search_vehicles_routing_parameters_request_1_grpc(): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_vehicles), + '__call__') as call: + call.return_value = vehicle_api.SearchVehiclesResponse() + client.search_vehicles(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.SearchVehiclesRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_kind_grpc_asyncio(): + transport = VehicleServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = VehicleServiceAsyncClient( + 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_create_vehicle_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.create_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.CreateVehicleRequest() + + 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_get_vehicle_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.get_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.GetVehicleRequest() + + 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_update_vehicle_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.update_vehicle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleRequest() + + 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_update_vehicle_attributes_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle_attributes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( + )) + await client.update_vehicle_attributes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleAttributesRequest() + + 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_list_vehicles_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_vehicles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.ListVehiclesRequest() + + 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_search_vehicles_empty_call_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( + )) + await client.search_vehicles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = vehicle_api.SearchVehiclesRequest() + + assert args[0] == request_msg + + +@pytest.mark.asyncio +async def test_create_vehicle_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.create_vehicle(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.CreateVehicleRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_get_vehicle_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.get_vehicle(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.GetVehicleRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_update_vehicle_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( + name='name_value', + vehicle_state=vehicles.VehicleState.OFFLINE, + supported_trip_types=[fleetengine.TripType.SHARED], + current_trips=['current_trips_value'], + maximum_capacity=1707, + current_route_segment='current_route_segment_value', + back_to_back_enabled=True, + navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, + )) + await client.update_vehicle(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_update_vehicle_attributes_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_vehicle_attributes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( + )) + await client.update_vehicle_attributes(request={"name": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.UpdateVehicleAttributesRequest(**{"name": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_list_vehicles_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_vehicles(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.ListVehiclesRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + +@pytest.mark.asyncio +async def test_search_vehicles_routing_parameters_request_1_grpc_asyncio(): + client = VehicleServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.search_vehicles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( + )) + await client.search_vehicles(request={"parent": "providers/sample1"}) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, kw = call.mock_calls[0] + request_msg = vehicle_api.SearchVehiclesRequest(**{"parent": "providers/sample1"}) + + assert args[0] == request_msg + + expected_headers = {'provider_id': 'providers/sample1'} + assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VehicleServiceGrpcTransport, + ) + +def test_vehicle_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VehicleServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_vehicle_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.VehicleServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_vehicle', + 'get_vehicle', + 'update_vehicle', + 'update_vehicle_attributes', + 'list_vehicles', + 'search_vehicles', + ) + 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_vehicle_service_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.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VehicleServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_vehicle_service_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.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VehicleServiceTransport() + adc.assert_called_once() + + +def test_vehicle_service_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) + VehicleServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VehicleServiceGrpcTransport, + transports.VehicleServiceGrpcAsyncIOTransport, + ], +) +def test_vehicle_service_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=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VehicleServiceGrpcTransport, + transports.VehicleServiceGrpcAsyncIOTransport, + ], +) +def test_vehicle_service_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.VehicleServiceGrpcTransport, grpc_helpers), + (transports.VehicleServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_vehicle_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "fleetengine.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="fleetengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) +def test_vehicle_service_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 + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_vehicle_service_host_no_port(transport_name): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'fleetengine.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_vehicle_service_host_with_port(transport_name): + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'fleetengine.googleapis.com:8000' + ) + +def test_vehicle_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VehicleServiceGrpcTransport( + 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_vehicle_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VehicleServiceGrpcAsyncIOTransport( + 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.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) +def test_vehicle_service_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.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) +def test_vehicle_service_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_vehicle_path(): + provider = "squid" + vehicle = "clam" + expected = "providers/{provider}/vehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) + actual = VehicleServiceClient.vehicle_path(provider, vehicle) + assert expected == actual + + +def test_parse_vehicle_path(): + expected = { + "provider": "whelk", + "vehicle": "octopus", + } + path = VehicleServiceClient.vehicle_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.parse_vehicle_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = VehicleServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = VehicleServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = VehicleServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = VehicleServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = VehicleServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = VehicleServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = VehicleServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = VehicleServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = VehicleServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = VehicleServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VehicleServiceClient.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.VehicleServiceTransport, '_prep_wrapped_messages') as prep: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.VehicleServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = VehicleServiceClient.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 = VehicleServiceClient( + 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 = VehicleServiceAsyncClient( + 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_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = VehicleServiceClient( + 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", [ + (VehicleServiceClient, transports.VehicleServiceGrpcTransport), + (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport), +]) +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 2b382c41519eb94e0981d09278b4564d926e4708 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 10 Dec 2024 00:01: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-fleetengine/v1/.coveragerc | 13 - .../google-maps-fleetengine/v1/.flake8 | 33 - .../google-maps-fleetengine/v1/MANIFEST.in | 2 - .../google-maps-fleetengine/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../google-maps-fleetengine/v1/docs/conf.py | 376 -- .../v1/docs/fleetengine_v1/services_.rst | 7 - .../v1/docs/fleetengine_v1/trip_service.rst | 10 - .../v1/docs/fleetengine_v1/types_.rst | 6 - .../docs/fleetengine_v1/vehicle_service.rst | 10 - .../google-maps-fleetengine/v1/docs/index.rst | 7 - .../v1/google/maps/fleetengine/__init__.py | 123 - .../google/maps/fleetengine/gapic_version.py | 16 - .../v1/google/maps/fleetengine/py.typed | 2 - .../v1/google/maps/fleetengine_v1/__init__.py | 124 - .../maps/fleetengine_v1/gapic_metadata.json | 147 - .../maps/fleetengine_v1/gapic_version.py | 16 - .../v1/google/maps/fleetengine_v1/py.typed | 2 - .../maps/fleetengine_v1/services/__init__.py | 15 - .../services/trip_service/__init__.py | 22 - .../services/trip_service/async_client.py | 675 ---- .../services/trip_service/client.py | 1003 ----- .../services/trip_service/pagers.py | 163 - .../trip_service/transports/README.rst | 9 - .../trip_service/transports/__init__.py | 33 - .../services/trip_service/transports/base.py | 248 -- .../services/trip_service/transports/grpc.py | 377 -- .../trip_service/transports/grpc_asyncio.py | 454 --- .../services/vehicle_service/__init__.py | 22 - .../services/vehicle_service/async_client.py | 827 ----- .../services/vehicle_service/client.py | 1155 ------ .../services/vehicle_service/pagers.py | 163 - .../vehicle_service/transports/README.rst | 9 - .../vehicle_service/transports/__init__.py | 33 - .../vehicle_service/transports/base.py | 270 -- .../vehicle_service/transports/grpc.py | 455 --- .../transports/grpc_asyncio.py | 546 --- .../maps/fleetengine_v1/types/__init__.py | 124 - .../maps/fleetengine_v1/types/fleetengine.py | 628 ---- .../maps/fleetengine_v1/types/header.py | 168 - .../maps/fleetengine_v1/types/traffic.py | 108 - .../maps/fleetengine_v1/types/trip_api.py | 460 --- .../google/maps/fleetengine_v1/types/trips.py | 490 --- .../maps/fleetengine_v1/types/vehicle_api.py | 1047 ------ .../maps/fleetengine_v1/types/vehicles.py | 580 --- .../google-maps-fleetengine/v1/mypy.ini | 3 - .../google-maps-fleetengine/v1/noxfile.py | 280 -- ...enerated_trip_service_create_trip_async.py | 53 - ...generated_trip_service_create_trip_sync.py | 53 - ...1_generated_trip_service_get_trip_async.py | 52 - ...v1_generated_trip_service_get_trip_sync.py | 52 - ...trip_service_report_billable_trip_async.py | 51 - ..._trip_service_report_billable_trip_sync.py | 51 - ...nerated_trip_service_search_trips_async.py | 53 - ...enerated_trip_service_search_trips_sync.py | 53 - ...enerated_trip_service_update_trip_async.py | 52 - ...generated_trip_service_update_trip_sync.py | 52 - ...ed_vehicle_service_create_vehicle_async.py | 53 - ...ted_vehicle_service_create_vehicle_sync.py | 53 - ...rated_vehicle_service_get_vehicle_async.py | 52 - ...erated_vehicle_service_get_vehicle_sync.py | 52 - ...ted_vehicle_service_list_vehicles_async.py | 54 - ...ated_vehicle_service_list_vehicles_sync.py | 54 - ...d_vehicle_service_search_vehicles_async.py | 57 - ...ed_vehicle_service_search_vehicles_sync.py | 57 - ...ed_vehicle_service_update_vehicle_async.py | 52 - ...service_update_vehicle_attributes_async.py | 56 - ..._service_update_vehicle_attributes_sync.py | 56 - ...ted_vehicle_service_update_vehicle_sync.py | 52 - .../snippet_metadata_maps.fleetengine.v1.json | 1692 --------- .../scripts/fixup_fleetengine_v1_keywords.py | 186 - .../google-maps-fleetengine/v1/setup.py | 99 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.13.txt | 7 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/fleetengine_v1/__init__.py | 16 - .../gapic/fleetengine_v1/test_trip_service.py | 3025 --------------- .../fleetengine_v1/test_vehicle_service.py | 3280 ----------------- .../google/maps/fleetengine/gapic_version.py | 2 +- .../maps/fleetengine_v1/gapic_version.py | 2 +- .../maps/fleetengine_v1/types/vehicle_api.py | 11 +- .../snippet_metadata_maps.fleetengine.v1.json | 2 +- 89 files changed, 7 insertions(+), 20892 deletions(-) delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/.coveragerc delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/.flake8 delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/README.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/mypy.ini delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/noxfile.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/setup.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py delete mode 100644 owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py diff --git a/owl-bot-staging/google-maps-fleetengine/v1/.coveragerc b/owl-bot-staging/google-maps-fleetengine/v1/.coveragerc deleted file mode 100644 index 2611031f9d9f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/fleetengine/__init__.py - google/maps/fleetengine/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-fleetengine/v1/.flake8 b/owl-bot-staging/google-maps-fleetengine/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/.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-fleetengine/v1/MANIFEST.in b/owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in deleted file mode 100644 index 3dcb3007a4fb..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/fleetengine *.py -recursive-include google/maps/fleetengine_v1 *.py diff --git a/owl-bot-staging/google-maps-fleetengine/v1/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/README.rst deleted file mode 100644 index b9bd958ce86c..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Fleetengine 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 Fleetengine 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-fleetengine/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-fleetengine/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/docs/conf.py b/owl-bot-staging/google-maps-fleetengine/v1/docs/conf.py deleted file mode 100644 index de2c2c6df868..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine 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-fleetengine" -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-fleetengine-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-fleetengine.tex", - u"google-maps-fleetengine 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-fleetengine", - u"Google Maps Fleetengine 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-fleetengine", - u"google-maps-fleetengine Documentation", - author, - "google-maps-fleetengine", - "GAPIC library for Google Maps Fleetengine 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-fleetengine/v1/docs/fleetengine_v1/services_.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst deleted file mode 100644 index a23a0eb62775..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/services_.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Maps Fleetengine v1 API -=========================================== -.. toctree:: - :maxdepth: 2 - - trip_service - vehicle_service diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst deleted file mode 100644 index 9cb42aff9bcf..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/trip_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -TripService ------------------------------ - -.. automodule:: google.maps.fleetengine_v1.services.trip_service - :members: - :inherited-members: - -.. automodule:: google.maps.fleetengine_v1.services.trip_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst deleted file mode 100644 index 2e980bba2916..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Fleetengine v1 API -======================================== - -.. automodule:: google.maps.fleetengine_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst deleted file mode 100644 index e1bfe924fcca..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/docs/fleetengine_v1/vehicle_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -VehicleService --------------------------------- - -.. automodule:: google.maps.fleetengine_v1.services.vehicle_service - :members: - :inherited-members: - -.. automodule:: google.maps.fleetengine_v1.services.vehicle_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst b/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst deleted file mode 100644 index 2b0090bf63a3..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - fleetengine_v1/services_ - fleetengine_v1/types_ diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py deleted file mode 100644 index 474efa60eda8..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/__init__.py +++ /dev/null @@ -1,123 +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.fleetengine import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.fleetengine_v1.services.trip_service.client import TripServiceClient -from google.maps.fleetengine_v1.services.trip_service.async_client import TripServiceAsyncClient -from google.maps.fleetengine_v1.services.vehicle_service.client import VehicleServiceClient -from google.maps.fleetengine_v1.services.vehicle_service.async_client import VehicleServiceAsyncClient - -from google.maps.fleetengine_v1.types.fleetengine import TerminalLocation -from google.maps.fleetengine_v1.types.fleetengine import TerminalPointId -from google.maps.fleetengine_v1.types.fleetengine import TripWaypoint -from google.maps.fleetengine_v1.types.fleetengine import VehicleAttribute -from google.maps.fleetengine_v1.types.fleetengine import VehicleLocation -from google.maps.fleetengine_v1.types.fleetengine import LocationSensor -from google.maps.fleetengine_v1.types.fleetengine import NavigationStatus -from google.maps.fleetengine_v1.types.fleetengine import PolylineFormatType -from google.maps.fleetengine_v1.types.fleetengine import TripType -from google.maps.fleetengine_v1.types.fleetengine import WaypointType -from google.maps.fleetengine_v1.types.header import RequestHeader -from google.maps.fleetengine_v1.types.traffic import ConsumableTrafficPolyline -from google.maps.fleetengine_v1.types.traffic import SpeedReadingInterval -from google.maps.fleetengine_v1.types.trip_api import CreateTripRequest -from google.maps.fleetengine_v1.types.trip_api import GetTripRequest -from google.maps.fleetengine_v1.types.trip_api import ReportBillableTripRequest -from google.maps.fleetengine_v1.types.trip_api import SearchTripsRequest -from google.maps.fleetengine_v1.types.trip_api import SearchTripsResponse -from google.maps.fleetengine_v1.types.trip_api import UpdateTripRequest -from google.maps.fleetengine_v1.types.trips import StopLocation -from google.maps.fleetengine_v1.types.trips import Trip -from google.maps.fleetengine_v1.types.trips import BillingPlatformIdentifier -from google.maps.fleetengine_v1.types.trips import TripStatus -from google.maps.fleetengine_v1.types.trips import TripView -from google.maps.fleetengine_v1.types.vehicle_api import CreateVehicleRequest -from google.maps.fleetengine_v1.types.vehicle_api import GetVehicleRequest -from google.maps.fleetengine_v1.types.vehicle_api import ListVehiclesRequest -from google.maps.fleetengine_v1.types.vehicle_api import ListVehiclesResponse -from google.maps.fleetengine_v1.types.vehicle_api import SearchVehiclesRequest -from google.maps.fleetengine_v1.types.vehicle_api import SearchVehiclesResponse -from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleAttributesRequest -from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleAttributesResponse -from google.maps.fleetengine_v1.types.vehicle_api import UpdateVehicleRequest -from google.maps.fleetengine_v1.types.vehicle_api import VehicleAttributeList -from google.maps.fleetengine_v1.types.vehicle_api import VehicleMatch -from google.maps.fleetengine_v1.types.vehicle_api import Waypoint -from google.maps.fleetengine_v1.types.vehicles import BatteryInfo -from google.maps.fleetengine_v1.types.vehicles import DeviceSettings -from google.maps.fleetengine_v1.types.vehicles import LicensePlate -from google.maps.fleetengine_v1.types.vehicles import TrafficPolylineData -from google.maps.fleetengine_v1.types.vehicles import Vehicle -from google.maps.fleetengine_v1.types.vehicles import VisualTrafficReportPolylineRendering -from google.maps.fleetengine_v1.types.vehicles import BatteryStatus -from google.maps.fleetengine_v1.types.vehicles import LocationPowerSaveMode -from google.maps.fleetengine_v1.types.vehicles import PowerSource -from google.maps.fleetengine_v1.types.vehicles import VehicleState - -__all__ = ('TripServiceClient', - 'TripServiceAsyncClient', - 'VehicleServiceClient', - 'VehicleServiceAsyncClient', - 'TerminalLocation', - 'TerminalPointId', - 'TripWaypoint', - 'VehicleAttribute', - 'VehicleLocation', - 'LocationSensor', - 'NavigationStatus', - 'PolylineFormatType', - 'TripType', - 'WaypointType', - 'RequestHeader', - 'ConsumableTrafficPolyline', - 'SpeedReadingInterval', - 'CreateTripRequest', - 'GetTripRequest', - 'ReportBillableTripRequest', - 'SearchTripsRequest', - 'SearchTripsResponse', - 'UpdateTripRequest', - 'StopLocation', - 'Trip', - 'BillingPlatformIdentifier', - 'TripStatus', - 'TripView', - 'CreateVehicleRequest', - 'GetVehicleRequest', - 'ListVehiclesRequest', - 'ListVehiclesResponse', - 'SearchVehiclesRequest', - 'SearchVehiclesResponse', - 'UpdateVehicleAttributesRequest', - 'UpdateVehicleAttributesResponse', - 'UpdateVehicleRequest', - 'VehicleAttributeList', - 'VehicleMatch', - 'Waypoint', - 'BatteryInfo', - 'DeviceSettings', - 'LicensePlate', - 'TrafficPolylineData', - 'Vehicle', - 'VisualTrafficReportPolylineRendering', - 'BatteryStatus', - 'LocationPowerSaveMode', - 'PowerSource', - 'VehicleState', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/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-fleetengine/v1/google/maps/fleetengine/py.typed b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed deleted file mode 100644 index 47d8e9910cb6..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-fleetengine package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py deleted file mode 100644 index 74f5cd53382b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/__init__.py +++ /dev/null @@ -1,124 +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.fleetengine_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.trip_service import TripServiceClient -from .services.trip_service import TripServiceAsyncClient -from .services.vehicle_service import VehicleServiceClient -from .services.vehicle_service import VehicleServiceAsyncClient - -from .types.fleetengine import TerminalLocation -from .types.fleetengine import TerminalPointId -from .types.fleetengine import TripWaypoint -from .types.fleetengine import VehicleAttribute -from .types.fleetengine import VehicleLocation -from .types.fleetengine import LocationSensor -from .types.fleetengine import NavigationStatus -from .types.fleetengine import PolylineFormatType -from .types.fleetengine import TripType -from .types.fleetengine import WaypointType -from .types.header import RequestHeader -from .types.traffic import ConsumableTrafficPolyline -from .types.traffic import SpeedReadingInterval -from .types.trip_api import CreateTripRequest -from .types.trip_api import GetTripRequest -from .types.trip_api import ReportBillableTripRequest -from .types.trip_api import SearchTripsRequest -from .types.trip_api import SearchTripsResponse -from .types.trip_api import UpdateTripRequest -from .types.trips import StopLocation -from .types.trips import Trip -from .types.trips import BillingPlatformIdentifier -from .types.trips import TripStatus -from .types.trips import TripView -from .types.vehicle_api import CreateVehicleRequest -from .types.vehicle_api import GetVehicleRequest -from .types.vehicle_api import ListVehiclesRequest -from .types.vehicle_api import ListVehiclesResponse -from .types.vehicle_api import SearchVehiclesRequest -from .types.vehicle_api import SearchVehiclesResponse -from .types.vehicle_api import UpdateVehicleAttributesRequest -from .types.vehicle_api import UpdateVehicleAttributesResponse -from .types.vehicle_api import UpdateVehicleRequest -from .types.vehicle_api import VehicleAttributeList -from .types.vehicle_api import VehicleMatch -from .types.vehicle_api import Waypoint -from .types.vehicles import BatteryInfo -from .types.vehicles import DeviceSettings -from .types.vehicles import LicensePlate -from .types.vehicles import TrafficPolylineData -from .types.vehicles import Vehicle -from .types.vehicles import VisualTrafficReportPolylineRendering -from .types.vehicles import BatteryStatus -from .types.vehicles import LocationPowerSaveMode -from .types.vehicles import PowerSource -from .types.vehicles import VehicleState - -__all__ = ( - 'TripServiceAsyncClient', - 'VehicleServiceAsyncClient', -'BatteryInfo', -'BatteryStatus', -'BillingPlatformIdentifier', -'ConsumableTrafficPolyline', -'CreateTripRequest', -'CreateVehicleRequest', -'DeviceSettings', -'GetTripRequest', -'GetVehicleRequest', -'LicensePlate', -'ListVehiclesRequest', -'ListVehiclesResponse', -'LocationPowerSaveMode', -'LocationSensor', -'NavigationStatus', -'PolylineFormatType', -'PowerSource', -'ReportBillableTripRequest', -'RequestHeader', -'SearchTripsRequest', -'SearchTripsResponse', -'SearchVehiclesRequest', -'SearchVehiclesResponse', -'SpeedReadingInterval', -'StopLocation', -'TerminalLocation', -'TerminalPointId', -'TrafficPolylineData', -'Trip', -'TripServiceClient', -'TripStatus', -'TripType', -'TripView', -'TripWaypoint', -'UpdateTripRequest', -'UpdateVehicleAttributesRequest', -'UpdateVehicleAttributesResponse', -'UpdateVehicleRequest', -'Vehicle', -'VehicleAttribute', -'VehicleAttributeList', -'VehicleLocation', -'VehicleMatch', -'VehicleServiceClient', -'VehicleState', -'VisualTrafficReportPolylineRendering', -'Waypoint', -'WaypointType', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json deleted file mode 100644 index 1a6ac8f7d116..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_metadata.json +++ /dev/null @@ -1,147 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.fleetengine_v1", - "protoPackage": "maps.fleetengine.v1", - "schema": "1.0", - "services": { - "TripService": { - "clients": { - "grpc": { - "libraryClient": "TripServiceClient", - "rpcs": { - "CreateTrip": { - "methods": [ - "create_trip" - ] - }, - "GetTrip": { - "methods": [ - "get_trip" - ] - }, - "ReportBillableTrip": { - "methods": [ - "report_billable_trip" - ] - }, - "SearchTrips": { - "methods": [ - "search_trips" - ] - }, - "UpdateTrip": { - "methods": [ - "update_trip" - ] - } - } - }, - "grpc-async": { - "libraryClient": "TripServiceAsyncClient", - "rpcs": { - "CreateTrip": { - "methods": [ - "create_trip" - ] - }, - "GetTrip": { - "methods": [ - "get_trip" - ] - }, - "ReportBillableTrip": { - "methods": [ - "report_billable_trip" - ] - }, - "SearchTrips": { - "methods": [ - "search_trips" - ] - }, - "UpdateTrip": { - "methods": [ - "update_trip" - ] - } - } - } - } - }, - "VehicleService": { - "clients": { - "grpc": { - "libraryClient": "VehicleServiceClient", - "rpcs": { - "CreateVehicle": { - "methods": [ - "create_vehicle" - ] - }, - "GetVehicle": { - "methods": [ - "get_vehicle" - ] - }, - "ListVehicles": { - "methods": [ - "list_vehicles" - ] - }, - "SearchVehicles": { - "methods": [ - "search_vehicles" - ] - }, - "UpdateVehicle": { - "methods": [ - "update_vehicle" - ] - }, - "UpdateVehicleAttributes": { - "methods": [ - "update_vehicle_attributes" - ] - } - } - }, - "grpc-async": { - "libraryClient": "VehicleServiceAsyncClient", - "rpcs": { - "CreateVehicle": { - "methods": [ - "create_vehicle" - ] - }, - "GetVehicle": { - "methods": [ - "get_vehicle" - ] - }, - "ListVehicles": { - "methods": [ - "list_vehicles" - ] - }, - "SearchVehicles": { - "methods": [ - "search_vehicles" - ] - }, - "UpdateVehicle": { - "methods": [ - "update_vehicle" - ] - }, - "UpdateVehicleAttributes": { - "methods": [ - "update_vehicle_attributes" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/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-fleetengine/v1/google/maps/fleetengine_v1/py.typed b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed deleted file mode 100644 index 47d8e9910cb6..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-fleetengine package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/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-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__init__.py deleted file mode 100644 index 268b90139486..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/__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 TripServiceClient -from .async_client import TripServiceAsyncClient - -__all__ = ( - 'TripServiceClient', - 'TripServiceAsyncClient', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py deleted file mode 100644 index f32fa72743e2..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/async_client.py +++ /dev/null @@ -1,675 +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, Sequence, Tuple, Type, Union - -from google.maps.fleetengine_v1 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.fleetengine_v1.services.trip_service import pagers -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import traffic -from google.maps.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -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.type import latlng_pb2 # type: ignore -from .transports.base import TripServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TripServiceGrpcAsyncIOTransport -from .client import TripServiceClient - - -class TripServiceAsyncClient: - """Trip management service.""" - - _client: TripServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = TripServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TripServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = TripServiceClient._DEFAULT_UNIVERSE - - trip_path = staticmethod(TripServiceClient.trip_path) - parse_trip_path = staticmethod(TripServiceClient.parse_trip_path) - common_billing_account_path = staticmethod(TripServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TripServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TripServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(TripServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(TripServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(TripServiceClient.parse_common_organization_path) - common_project_path = staticmethod(TripServiceClient.common_project_path) - parse_common_project_path = staticmethod(TripServiceClient.parse_common_project_path) - common_location_path = staticmethod(TripServiceClient.common_location_path) - parse_common_location_path = staticmethod(TripServiceClient.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: - TripServiceAsyncClient: The constructed client. - """ - return TripServiceClient.from_service_account_info.__func__(TripServiceAsyncClient, 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: - TripServiceAsyncClient: The constructed client. - """ - return TripServiceClient.from_service_account_file.__func__(TripServiceAsyncClient, 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 TripServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> TripServiceTransport: - """Returns the transport used by the client instance. - - Returns: - TripServiceTransport: 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 = TripServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TripServiceTransport, Callable[..., TripServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the trip service 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,TripServiceTransport,Callable[..., TripServiceTransport]]]): - 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 TripServiceTransport 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 = TripServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_trip(self, - request: Optional[Union[trip_api.CreateTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Creates a trip in the Fleet Engine and returns the - new trip. - - .. 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 fleetengine_v1 - - async def sample_create_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateTripRequest( - parent="parent_value", - trip_id="trip_id_value", - ) - - # Make the request - response = await client.create_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.CreateTripRequest, dict]]): - The request object. CreateTrip 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.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.CreateTripRequest): - request = trip_api.CreateTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 - - async def get_trip(self, - request: Optional[Union[trip_api.GetTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Get information about a single trip. - - .. 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 fleetengine_v1 - - async def sample_get_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetTripRequest( - name="name_value", - ) - - # Make the request - response = await client.get_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.GetTripRequest, dict]]): - The request object. GetTrip 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.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.GetTripRequest): - request = trip_api.GetTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 - - async def report_billable_trip(self, - request: Optional[Union[trip_api.ReportBillableTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Report billable trip usage. - - .. 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 fleetengine_v1 - - async def sample_report_billable_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.ReportBillableTripRequest( - name="name_value", - country_code="country_code_value", - ) - - # Make the request - await client.report_billable_trip(request=request) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.ReportBillableTripRequest, dict]]): - The request object. ReportBillableTrip 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. - """ - # 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, trip_api.ReportBillableTripRequest): - request = trip_api.ReportBillableTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.report_billable_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def search_trips(self, - request: Optional[Union[trip_api.SearchTripsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchTripsAsyncPager: - r"""Get all the trips for a specific vehicle. - - .. 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 fleetengine_v1 - - async def sample_search_trips(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchTripsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_trips(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.SearchTripsRequest, dict]]): - The request object. SearchTrips 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.fleetengine_v1.services.trip_service.pagers.SearchTripsAsyncPager: - SearchTrips response message. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # 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, trip_api.SearchTripsRequest): - request = trip_api.SearchTripsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.search_trips] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchTripsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_trip(self, - request: Optional[Union[trip_api.UpdateTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Updates trip data. - - .. 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 fleetengine_v1 - - async def sample_update_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateTripRequest( - name="name_value", - ) - - # Make the request - response = await client.update_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.UpdateTripRequest, dict]]): - The request object. UpdateTrip 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.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.UpdateTripRequest): - request = trip_api.UpdateTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 - - async def __aenter__(self) -> "TripServiceAsyncClient": - 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__ = ( - "TripServiceAsyncClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py deleted file mode 100644 index f2b473dd70b3..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/client.py +++ /dev/null @@ -1,1003 +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, Sequence, Tuple, Type, Union, cast -import warnings - -from google.maps.fleetengine_v1 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.fleetengine_v1.services.trip_service import pagers -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import traffic -from google.maps.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -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.type import latlng_pb2 # type: ignore -from .transports.base import TripServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import TripServiceGrpcTransport -from .transports.grpc_asyncio import TripServiceGrpcAsyncIOTransport - - -class TripServiceClientMeta(type): - """Metaclass for the TripService 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[TripServiceTransport]] - _transport_registry["grpc"] = TripServiceGrpcTransport - _transport_registry["grpc_asyncio"] = TripServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[TripServiceTransport]: - """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 TripServiceClient(metaclass=TripServiceClientMeta): - """Trip management service.""" - - @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 = "fleetengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "fleetengine.{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: - TripServiceClient: 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: - TripServiceClient: 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) -> TripServiceTransport: - """Returns the transport used by the client instance. - - Returns: - TripServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def trip_path(provider: str,trip: str,) -> str: - """Returns a fully-qualified trip string.""" - return "providers/{provider}/trips/{trip}".format(provider=provider, trip=trip, ) - - @staticmethod - def parse_trip_path(path: str) -> Dict[str,str]: - """Parses a trip path into its component segments.""" - m = re.match(r"^providers/(?P.+?)/trips/(?P.+?)$", path) - return m.groupdict() if m else {} - - @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 = TripServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = TripServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = TripServiceClient._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 = TripServiceClient._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, TripServiceTransport, Callable[..., TripServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the trip service 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,TripServiceTransport,Callable[..., TripServiceTransport]]]): - 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 TripServiceTransport 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 = TripServiceClient._read_environment_variables() - self._client_cert_source = TripServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = TripServiceClient._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, TripServiceTransport) - if transport_provided: - # transport is a TripServiceTransport 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(TripServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - TripServiceClient._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[TripServiceTransport], Callable[..., TripServiceTransport]] = ( - TripServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., TripServiceTransport], 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 create_trip(self, - request: Optional[Union[trip_api.CreateTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Creates a trip in the Fleet Engine and returns the - new trip. - - .. 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 fleetengine_v1 - - def sample_create_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateTripRequest( - parent="parent_value", - trip_id="trip_id_value", - ) - - # Make the request - response = client.create_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.CreateTripRequest, dict]): - The request object. CreateTrip 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.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.CreateTripRequest): - request = trip_api.CreateTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 get_trip(self, - request: Optional[Union[trip_api.GetTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Get information about a single trip. - - .. 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 fleetengine_v1 - - def sample_get_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetTripRequest( - name="name_value", - ) - - # Make the request - response = client.get_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.GetTripRequest, dict]): - The request object. GetTrip 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.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.GetTripRequest): - request = trip_api.GetTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 report_billable_trip(self, - request: Optional[Union[trip_api.ReportBillableTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Report billable trip usage. - - .. 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 fleetengine_v1 - - def sample_report_billable_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.ReportBillableTripRequest( - name="name_value", - country_code="country_code_value", - ) - - # Make the request - client.report_billable_trip(request=request) - - Args: - request (Union[google.maps.fleetengine_v1.types.ReportBillableTripRequest, dict]): - The request object. ReportBillableTrip 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. - """ - # 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, trip_api.ReportBillableTripRequest): - request = trip_api.ReportBillableTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.report_billable_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def search_trips(self, - request: Optional[Union[trip_api.SearchTripsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchTripsPager: - r"""Get all the trips for a specific vehicle. - - .. 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 fleetengine_v1 - - def sample_search_trips(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchTripsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_trips(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.SearchTripsRequest, dict]): - The request object. SearchTrips 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.fleetengine_v1.services.trip_service.pagers.SearchTripsPager: - SearchTrips response message. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # 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, trip_api.SearchTripsRequest): - request = trip_api.SearchTripsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_trips] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchTripsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_trip(self, - request: Optional[Union[trip_api.UpdateTripRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> trips.Trip: - r"""Updates trip data. - - .. 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 fleetengine_v1 - - def sample_update_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateTripRequest( - name="name_value", - ) - - # Make the request - response = client.update_trip(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.UpdateTripRequest, dict]): - The request object. UpdateTrip 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.fleetengine_v1.types.Trip: - Trip metadata. - """ - # 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, trip_api.UpdateTripRequest): - request = trip_api.UpdateTripRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_trip] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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) -> "TripServiceClient": - 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__ = ( - "TripServiceClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py deleted file mode 100644 index 8b5599f99cfa..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/pagers.py +++ /dev/null @@ -1,163 +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.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.maps.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips - - -class SearchTripsPager: - """A pager for iterating through ``search_trips`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``trips`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchTrips`` requests and continue to iterate - through the ``trips`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., trip_api.SearchTripsResponse], - request: trip_api.SearchTripsRequest, - response: trip_api.SearchTripsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_v1.types.SearchTripsRequest): - The initial request object. - response (google.maps.fleetengine_v1.types.SearchTripsResponse): - The initial response object. - 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. - """ - self._method = method - self._request = trip_api.SearchTripsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[trip_api.SearchTripsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[trips.Trip]: - for page in self.pages: - yield from page.trips - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchTripsAsyncPager: - """A pager for iterating through ``search_trips`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``trips`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchTrips`` requests and continue to iterate - through the ``trips`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_v1.types.SearchTripsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[trip_api.SearchTripsResponse]], - request: trip_api.SearchTripsRequest, - response: trip_api.SearchTripsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_v1.types.SearchTripsRequest): - The initial request object. - response (google.maps.fleetengine_v1.types.SearchTripsResponse): - The initial response object. - retry (google.api_core.retry.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. - """ - self._method = method - self._request = trip_api.SearchTripsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[trip_api.SearchTripsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[trips.Trip]: - async def async_generator(): - async for page in self.pages: - for response in page.trips: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst deleted file mode 100644 index 97675873407f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`TripServiceTransport` is the ABC for all transports. -- public child `TripServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `TripServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseTripServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `TripServiceRestTransport` 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-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py deleted file mode 100644 index 89de6013d759..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/__init__.py +++ /dev/null @@ -1,33 +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 TripServiceTransport -from .grpc import TripServiceGrpcTransport -from .grpc_asyncio import TripServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TripServiceTransport]] -_transport_registry['grpc'] = TripServiceGrpcTransport -_transport_registry['grpc_asyncio'] = TripServiceGrpcAsyncIOTransport - -__all__ = ( - 'TripServiceTransport', - 'TripServiceGrpcTransport', - 'TripServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py deleted file mode 100644 index 71595601d903..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/base.py +++ /dev/null @@ -1,248 +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.fleetengine_v1 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.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class TripServiceTransport(abc.ABC): - """Abstract transport class for TripService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'fleetengine.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: 'fleetengine.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.create_trip: gapic_v1.method.wrap_method( - self.create_trip, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.get_trip: gapic_v1.method.wrap_method( - self.get_trip, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.report_billable_trip: gapic_v1.method.wrap_method( - self.report_billable_trip, - default_timeout=None, - client_info=client_info, - ), - self.search_trips: gapic_v1.method.wrap_method( - self.search_trips, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_trip: gapic_v1.method.wrap_method( - self.update_trip, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - 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 create_trip(self) -> Callable[ - [trip_api.CreateTripRequest], - Union[ - trips.Trip, - Awaitable[trips.Trip] - ]]: - raise NotImplementedError() - - @property - def get_trip(self) -> Callable[ - [trip_api.GetTripRequest], - Union[ - trips.Trip, - Awaitable[trips.Trip] - ]]: - raise NotImplementedError() - - @property - def report_billable_trip(self) -> Callable[ - [trip_api.ReportBillableTripRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def search_trips(self) -> Callable[ - [trip_api.SearchTripsRequest], - Union[ - trip_api.SearchTripsResponse, - Awaitable[trip_api.SearchTripsResponse] - ]]: - raise NotImplementedError() - - @property - def update_trip(self) -> Callable[ - [trip_api.UpdateTripRequest], - Union[ - trips.Trip, - Awaitable[trips.Trip] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'TripServiceTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py deleted file mode 100644 index 0c20dd7934fc..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py +++ /dev/null @@ -1,377 +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.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -from google.protobuf import empty_pb2 # type: ignore -from .base import TripServiceTransport, DEFAULT_CLIENT_INFO - - -class TripServiceGrpcTransport(TripServiceTransport): - """gRPC backend transport for TripService. - - Trip management service. - - 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 = 'fleetengine.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: 'fleetengine.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 = 'fleetengine.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 create_trip(self) -> Callable[ - [trip_api.CreateTripRequest], - trips.Trip]: - r"""Return a callable for the create trip method over gRPC. - - Creates a trip in the Fleet Engine and returns the - new trip. - - Returns: - Callable[[~.CreateTripRequest], - ~.Trip]: - 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 'create_trip' not in self._stubs: - self._stubs['create_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/CreateTrip', - request_serializer=trip_api.CreateTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['create_trip'] - - @property - def get_trip(self) -> Callable[ - [trip_api.GetTripRequest], - trips.Trip]: - r"""Return a callable for the get trip method over gRPC. - - Get information about a single trip. - - Returns: - Callable[[~.GetTripRequest], - ~.Trip]: - 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 'get_trip' not in self._stubs: - self._stubs['get_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/GetTrip', - request_serializer=trip_api.GetTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['get_trip'] - - @property - def report_billable_trip(self) -> Callable[ - [trip_api.ReportBillableTripRequest], - empty_pb2.Empty]: - r"""Return a callable for the report billable trip method over gRPC. - - Report billable trip usage. - - Returns: - Callable[[~.ReportBillableTripRequest], - ~.Empty]: - 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 'report_billable_trip' not in self._stubs: - self._stubs['report_billable_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/ReportBillableTrip', - request_serializer=trip_api.ReportBillableTripRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['report_billable_trip'] - - @property - def search_trips(self) -> Callable[ - [trip_api.SearchTripsRequest], - trip_api.SearchTripsResponse]: - r"""Return a callable for the search trips method over gRPC. - - Get all the trips for a specific vehicle. - - Returns: - Callable[[~.SearchTripsRequest], - ~.SearchTripsResponse]: - 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 'search_trips' not in self._stubs: - self._stubs['search_trips'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/SearchTrips', - request_serializer=trip_api.SearchTripsRequest.serialize, - response_deserializer=trip_api.SearchTripsResponse.deserialize, - ) - return self._stubs['search_trips'] - - @property - def update_trip(self) -> Callable[ - [trip_api.UpdateTripRequest], - trips.Trip]: - r"""Return a callable for the update trip method over gRPC. - - Updates trip data. - - Returns: - Callable[[~.UpdateTripRequest], - ~.Trip]: - 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 'update_trip' not in self._stubs: - self._stubs['update_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/UpdateTrip', - request_serializer=trip_api.UpdateTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['update_trip'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'TripServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py deleted file mode 100644 index b7b838015e6d..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,454 +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.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -from google.protobuf import empty_pb2 # type: ignore -from .base import TripServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import TripServiceGrpcTransport - - -class TripServiceGrpcAsyncIOTransport(TripServiceTransport): - """gRPC AsyncIO backend transport for TripService. - - Trip management service. - - 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 = 'fleetengine.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 = 'fleetengine.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: 'fleetengine.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 create_trip(self) -> Callable[ - [trip_api.CreateTripRequest], - Awaitable[trips.Trip]]: - r"""Return a callable for the create trip method over gRPC. - - Creates a trip in the Fleet Engine and returns the - new trip. - - Returns: - Callable[[~.CreateTripRequest], - Awaitable[~.Trip]]: - 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 'create_trip' not in self._stubs: - self._stubs['create_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/CreateTrip', - request_serializer=trip_api.CreateTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['create_trip'] - - @property - def get_trip(self) -> Callable[ - [trip_api.GetTripRequest], - Awaitable[trips.Trip]]: - r"""Return a callable for the get trip method over gRPC. - - Get information about a single trip. - - Returns: - Callable[[~.GetTripRequest], - Awaitable[~.Trip]]: - 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 'get_trip' not in self._stubs: - self._stubs['get_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/GetTrip', - request_serializer=trip_api.GetTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['get_trip'] - - @property - def report_billable_trip(self) -> Callable[ - [trip_api.ReportBillableTripRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the report billable trip method over gRPC. - - Report billable trip usage. - - Returns: - Callable[[~.ReportBillableTripRequest], - Awaitable[~.Empty]]: - 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 'report_billable_trip' not in self._stubs: - self._stubs['report_billable_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/ReportBillableTrip', - request_serializer=trip_api.ReportBillableTripRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['report_billable_trip'] - - @property - def search_trips(self) -> Callable[ - [trip_api.SearchTripsRequest], - Awaitable[trip_api.SearchTripsResponse]]: - r"""Return a callable for the search trips method over gRPC. - - Get all the trips for a specific vehicle. - - Returns: - Callable[[~.SearchTripsRequest], - Awaitable[~.SearchTripsResponse]]: - 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 'search_trips' not in self._stubs: - self._stubs['search_trips'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/SearchTrips', - request_serializer=trip_api.SearchTripsRequest.serialize, - response_deserializer=trip_api.SearchTripsResponse.deserialize, - ) - return self._stubs['search_trips'] - - @property - def update_trip(self) -> Callable[ - [trip_api.UpdateTripRequest], - Awaitable[trips.Trip]]: - r"""Return a callable for the update trip method over gRPC. - - Updates trip data. - - Returns: - Callable[[~.UpdateTripRequest], - Awaitable[~.Trip]]: - 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 'update_trip' not in self._stubs: - self._stubs['update_trip'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.TripService/UpdateTrip', - request_serializer=trip_api.UpdateTripRequest.serialize, - response_deserializer=trips.Trip.deserialize, - ) - return self._stubs['update_trip'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.create_trip: self._wrap_method( - self.create_trip, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.get_trip: self._wrap_method( - self.get_trip, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.report_billable_trip: self._wrap_method( - self.report_billable_trip, - default_timeout=None, - client_info=client_info, - ), - self.search_trips: self._wrap_method( - self.search_trips, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_trip: self._wrap_method( - self.update_trip, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - 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__ = ( - 'TripServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__init__.py deleted file mode 100644 index fc6cb2c02da7..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/__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 VehicleServiceClient -from .async_client import VehicleServiceAsyncClient - -__all__ = ( - 'VehicleServiceClient', - 'VehicleServiceAsyncClient', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py deleted file mode 100644 index f5dcf834487a..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/async_client.py +++ /dev/null @@ -1,827 +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, Sequence, Tuple, Type, Union - -from google.maps.fleetengine_v1 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.fleetengine_v1.services.vehicle_service import pagers -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import VehicleServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import VehicleServiceGrpcAsyncIOTransport -from .client import VehicleServiceClient - - -class VehicleServiceAsyncClient: - """Vehicle management service.""" - - _client: VehicleServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = VehicleServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = VehicleServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = VehicleServiceClient._DEFAULT_UNIVERSE - - vehicle_path = staticmethod(VehicleServiceClient.vehicle_path) - parse_vehicle_path = staticmethod(VehicleServiceClient.parse_vehicle_path) - common_billing_account_path = staticmethod(VehicleServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(VehicleServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(VehicleServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(VehicleServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(VehicleServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(VehicleServiceClient.parse_common_organization_path) - common_project_path = staticmethod(VehicleServiceClient.common_project_path) - parse_common_project_path = staticmethod(VehicleServiceClient.parse_common_project_path) - common_location_path = staticmethod(VehicleServiceClient.common_location_path) - parse_common_location_path = staticmethod(VehicleServiceClient.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: - VehicleServiceAsyncClient: The constructed client. - """ - return VehicleServiceClient.from_service_account_info.__func__(VehicleServiceAsyncClient, 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: - VehicleServiceAsyncClient: The constructed client. - """ - return VehicleServiceClient.from_service_account_file.__func__(VehicleServiceAsyncClient, 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 VehicleServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> VehicleServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VehicleServiceTransport: 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 = VehicleServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, VehicleServiceTransport, Callable[..., VehicleServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the vehicle service 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,VehicleServiceTransport,Callable[..., VehicleServiceTransport]]]): - 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 VehicleServiceTransport 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 = VehicleServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_vehicle(self, - request: Optional[Union[vehicle_api.CreateVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Instantiates a new vehicle associated with an on-demand - rideshare or deliveries provider. Each ``Vehicle`` must have a - unique vehicle ID. - - The following ``Vehicle`` fields are required when creating a - ``Vehicle``: - - - ``vehicleState`` - - ``supportedTripTypes`` - - ``maximumCapacity`` - - ``vehicleType`` - - The following ``Vehicle`` fields are ignored when creating a - ``Vehicle``: - - - ``name`` - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_version`` - - ``current_route_segment_traffic`` - - ``route`` - - ``waypoints`` - - ``waypoints_version`` - - ``remaining_distance_meters`` - - ``remaining_time_seconds`` - - ``eta_to_next_waypoint`` - - ``navigation_status`` - - All other fields are optional and used if provided. - - .. 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 fleetengine_v1 - - async def sample_create_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateVehicleRequest( - parent="parent_value", - vehicle_id="vehicle_id_value", - ) - - # Make the request - response = await client.create_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.CreateVehicleRequest, dict]]): - The request object. ``CreateVehicle`` 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.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.CreateVehicleRequest): - request = vehicle_api.CreateVehicleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 - - async def get_vehicle(self, - request: Optional[Union[vehicle_api.GetVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Returns a vehicle from the Fleet Engine. - - .. 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 fleetengine_v1 - - async def sample_get_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.GetVehicleRequest, dict]]): - The request object. ``GetVehicle`` 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.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.GetVehicleRequest): - request = vehicle_api.GetVehicleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 - - async def update_vehicle(self, - request: Optional[Union[vehicle_api.UpdateVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Writes updated vehicle data to the Fleet Engine. - - When updating a ``Vehicle``, the following fields cannot be - updated since they are managed by the server: - - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment_version`` - - ``waypoints_version`` - - The vehicle ``name`` also cannot be updated. - - If the ``attributes`` field is updated, **all** the vehicle's - attributes are replaced with the attributes provided in the - request. If you want to update only some attributes, see the - ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` - field can be updated, but must contain all the waypoints - currently on the vehicle, and no other waypoints. - - .. 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 fleetengine_v1 - - async def sample_update_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.update_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.UpdateVehicleRequest, dict]]): - The request object. \`UpdateVehicle 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.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.UpdateVehicleRequest): - request = vehicle_api.UpdateVehicleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 - - async def update_vehicle_attributes(self, - request: Optional[Union[vehicle_api.UpdateVehicleAttributesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicle_api.UpdateVehicleAttributesResponse: - r"""Partially updates a vehicle's attributes. Only the attributes - mentioned in the request will be updated, other attributes will - NOT be altered. Note: this is different in ``UpdateVehicle``, - where the whole ``attributes`` field will be replaced by the one - in ``UpdateVehicleRequest``, attributes not in the request would - be removed. - - .. 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 fleetengine_v1 - - async def sample_update_vehicle_attributes(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - attributes = fleetengine_v1.VehicleAttribute() - attributes.string_value = "string_value_value" - - request = fleetengine_v1.UpdateVehicleAttributesRequest( - name="name_value", - attributes=attributes, - ) - - # Make the request - response = await client.update_vehicle_attributes(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest, dict]]): - The request object. ``UpdateVehicleAttributes`` 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.fleetengine_v1.types.UpdateVehicleAttributesResponse: - UpdateVehicleAttributes 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, vehicle_api.UpdateVehicleAttributesRequest): - request = vehicle_api.UpdateVehicleAttributesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_vehicle_attributes] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 - - async def list_vehicles(self, - request: Optional[Union[vehicle_api.ListVehiclesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVehiclesAsyncPager: - r"""Returns a paginated list of vehicles associated with - a provider that match the request options. - - .. 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 fleetengine_v1 - - async def sample_list_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.ListVehiclesRequest( - parent="parent_value", - vehicle_type_categories=['PEDESTRIAN'], - ) - - # Make the request - page_result = client.list_vehicles(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.ListVehiclesRequest, dict]]): - The request object. ``ListVehicles`` 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.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesAsyncPager: - ListVehicles response message. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # 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, vehicle_api.ListVehiclesRequest): - request = vehicle_api.ListVehiclesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_vehicles] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListVehiclesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def search_vehicles(self, - request: Optional[Union[vehicle_api.SearchVehiclesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicle_api.SearchVehiclesResponse: - r"""Returns a list of vehicles that match the request - options. - - .. 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 fleetengine_v1 - - async def sample_search_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = await client.search_vehicles(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.SearchVehiclesRequest, dict]]): - The request object. ``SearchVehicles`` 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.fleetengine_v1.types.SearchVehiclesResponse: - SearchVehicles 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, vehicle_api.SearchVehiclesRequest): - request = vehicle_api.SearchVehiclesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.search_vehicles] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 - - async def __aenter__(self) -> "VehicleServiceAsyncClient": - 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__ = ( - "VehicleServiceAsyncClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py deleted file mode 100644 index e88fa624c2d6..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/client.py +++ /dev/null @@ -1,1155 +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, Sequence, Tuple, Type, Union, cast -import warnings - -from google.maps.fleetengine_v1 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.fleetengine_v1.services.vehicle_service import pagers -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import VehicleServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import VehicleServiceGrpcTransport -from .transports.grpc_asyncio import VehicleServiceGrpcAsyncIOTransport - - -class VehicleServiceClientMeta(type): - """Metaclass for the VehicleService 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[VehicleServiceTransport]] - _transport_registry["grpc"] = VehicleServiceGrpcTransport - _transport_registry["grpc_asyncio"] = VehicleServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[VehicleServiceTransport]: - """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 VehicleServiceClient(metaclass=VehicleServiceClientMeta): - """Vehicle management service.""" - - @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 = "fleetengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "fleetengine.{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: - VehicleServiceClient: 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: - VehicleServiceClient: 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) -> VehicleServiceTransport: - """Returns the transport used by the client instance. - - Returns: - VehicleServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def vehicle_path(provider: str,vehicle: str,) -> str: - """Returns a fully-qualified vehicle string.""" - return "providers/{provider}/vehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) - - @staticmethod - def parse_vehicle_path(path: str) -> Dict[str,str]: - """Parses a vehicle path into its component segments.""" - m = re.match(r"^providers/(?P.+?)/vehicles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @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 = VehicleServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = VehicleServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = VehicleServiceClient._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 = VehicleServiceClient._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, VehicleServiceTransport, Callable[..., VehicleServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the vehicle service 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,VehicleServiceTransport,Callable[..., VehicleServiceTransport]]]): - 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 VehicleServiceTransport 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 = VehicleServiceClient._read_environment_variables() - self._client_cert_source = VehicleServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = VehicleServiceClient._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, VehicleServiceTransport) - if transport_provided: - # transport is a VehicleServiceTransport 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(VehicleServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - VehicleServiceClient._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[VehicleServiceTransport], Callable[..., VehicleServiceTransport]] = ( - VehicleServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., VehicleServiceTransport], 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 create_vehicle(self, - request: Optional[Union[vehicle_api.CreateVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Instantiates a new vehicle associated with an on-demand - rideshare or deliveries provider. Each ``Vehicle`` must have a - unique vehicle ID. - - The following ``Vehicle`` fields are required when creating a - ``Vehicle``: - - - ``vehicleState`` - - ``supportedTripTypes`` - - ``maximumCapacity`` - - ``vehicleType`` - - The following ``Vehicle`` fields are ignored when creating a - ``Vehicle``: - - - ``name`` - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_version`` - - ``current_route_segment_traffic`` - - ``route`` - - ``waypoints`` - - ``waypoints_version`` - - ``remaining_distance_meters`` - - ``remaining_time_seconds`` - - ``eta_to_next_waypoint`` - - ``navigation_status`` - - All other fields are optional and used if provided. - - .. 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 fleetengine_v1 - - def sample_create_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateVehicleRequest( - parent="parent_value", - vehicle_id="vehicle_id_value", - ) - - # Make the request - response = client.create_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.CreateVehicleRequest, dict]): - The request object. ``CreateVehicle`` 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.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.CreateVehicleRequest): - request = vehicle_api.CreateVehicleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 get_vehicle(self, - request: Optional[Union[vehicle_api.GetVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Returns a vehicle from the Fleet Engine. - - .. 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 fleetengine_v1 - - def sample_get_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.get_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.GetVehicleRequest, dict]): - The request object. ``GetVehicle`` 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.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.GetVehicleRequest): - request = vehicle_api.GetVehicleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 update_vehicle(self, - request: Optional[Union[vehicle_api.UpdateVehicleRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicles.Vehicle: - r"""Writes updated vehicle data to the Fleet Engine. - - When updating a ``Vehicle``, the following fields cannot be - updated since they are managed by the server: - - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment_version`` - - ``waypoints_version`` - - The vehicle ``name`` also cannot be updated. - - If the ``attributes`` field is updated, **all** the vehicle's - attributes are replaced with the attributes provided in the - request. If you want to update only some attributes, see the - ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` - field can be updated, but must contain all the waypoints - currently on the vehicle, and no other waypoints. - - .. 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 fleetengine_v1 - - def sample_update_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.update_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.UpdateVehicleRequest, dict]): - The request object. \`UpdateVehicle 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.fleetengine_v1.types.Vehicle: - Vehicle metadata. - """ - # 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, vehicle_api.UpdateVehicleRequest): - request = vehicle_api.UpdateVehicleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 update_vehicle_attributes(self, - request: Optional[Union[vehicle_api.UpdateVehicleAttributesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicle_api.UpdateVehicleAttributesResponse: - r"""Partially updates a vehicle's attributes. Only the attributes - mentioned in the request will be updated, other attributes will - NOT be altered. Note: this is different in ``UpdateVehicle``, - where the whole ``attributes`` field will be replaced by the one - in ``UpdateVehicleRequest``, attributes not in the request would - be removed. - - .. 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 fleetengine_v1 - - def sample_update_vehicle_attributes(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - attributes = fleetengine_v1.VehicleAttribute() - attributes.string_value = "string_value_value" - - request = fleetengine_v1.UpdateVehicleAttributesRequest( - name="name_value", - attributes=attributes, - ) - - # Make the request - response = client.update_vehicle_attributes(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest, dict]): - The request object. ``UpdateVehicleAttributes`` 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.fleetengine_v1.types.UpdateVehicleAttributesResponse: - UpdateVehicleAttributes 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, vehicle_api.UpdateVehicleAttributesRequest): - request = vehicle_api.UpdateVehicleAttributesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_vehicle_attributes] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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 list_vehicles(self, - request: Optional[Union[vehicle_api.ListVehiclesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVehiclesPager: - r"""Returns a paginated list of vehicles associated with - a provider that match the request options. - - .. 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 fleetengine_v1 - - def sample_list_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.ListVehiclesRequest( - parent="parent_value", - vehicle_type_categories=['PEDESTRIAN'], - ) - - # Make the request - page_result = client.list_vehicles(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.ListVehiclesRequest, dict]): - The request object. ``ListVehicles`` 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.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesPager: - ListVehicles response message. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # 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, vehicle_api.ListVehiclesRequest): - request = vehicle_api.ListVehiclesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_vehicles] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListVehiclesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def search_vehicles(self, - request: Optional[Union[vehicle_api.SearchVehiclesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicle_api.SearchVehiclesResponse: - r"""Returns a list of vehicles that match the request - options. - - .. 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 fleetengine_v1 - - def sample_search_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = client.search_vehicles(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.SearchVehiclesRequest, dict]): - The request object. ``SearchVehicles`` 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.fleetengine_v1.types.SearchVehiclesResponse: - SearchVehicles 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, vehicle_api.SearchVehiclesRequest): - request = vehicle_api.SearchVehiclesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_vehicles] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # 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) -> "VehicleServiceClient": - 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__ = ( - "VehicleServiceClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py deleted file mode 100644 index a37cce62d28f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/pagers.py +++ /dev/null @@ -1,163 +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.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.maps.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles - - -class ListVehiclesPager: - """A pager for iterating through ``list_vehicles`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``vehicles`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListVehicles`` requests and continue to iterate - through the ``vehicles`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., vehicle_api.ListVehiclesResponse], - request: vehicle_api.ListVehiclesRequest, - response: vehicle_api.ListVehiclesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_v1.types.ListVehiclesRequest): - The initial request object. - response (google.maps.fleetengine_v1.types.ListVehiclesResponse): - The initial response object. - 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. - """ - self._method = method - self._request = vehicle_api.ListVehiclesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[vehicle_api.ListVehiclesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[vehicles.Vehicle]: - for page in self.pages: - yield from page.vehicles - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListVehiclesAsyncPager: - """A pager for iterating through ``list_vehicles`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``vehicles`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListVehicles`` requests and continue to iterate - through the ``vehicles`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_v1.types.ListVehiclesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[vehicle_api.ListVehiclesResponse]], - request: vehicle_api.ListVehiclesRequest, - response: vehicle_api.ListVehiclesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_v1.types.ListVehiclesRequest): - The initial request object. - response (google.maps.fleetengine_v1.types.ListVehiclesResponse): - The initial response object. - retry (google.api_core.retry.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. - """ - self._method = method - self._request = vehicle_api.ListVehiclesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[vehicle_api.ListVehiclesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[vehicles.Vehicle]: - async def async_generator(): - async for page in self.pages: - for response in page.vehicles: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst deleted file mode 100644 index cab31a918dfd..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`VehicleServiceTransport` is the ABC for all transports. -- public child `VehicleServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `VehicleServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseVehicleServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `VehicleServiceRestTransport` 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-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py deleted file mode 100644 index 6c5e9251815c..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/__init__.py +++ /dev/null @@ -1,33 +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 VehicleServiceTransport -from .grpc import VehicleServiceGrpcTransport -from .grpc_asyncio import VehicleServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[VehicleServiceTransport]] -_transport_registry['grpc'] = VehicleServiceGrpcTransport -_transport_registry['grpc_asyncio'] = VehicleServiceGrpcAsyncIOTransport - -__all__ = ( - 'VehicleServiceTransport', - 'VehicleServiceGrpcTransport', - 'VehicleServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py deleted file mode 100644 index 7f3a046bb15d..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py +++ /dev/null @@ -1,270 +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.fleetengine_v1 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.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class VehicleServiceTransport(abc.ABC): - """Abstract transport class for VehicleService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'fleetengine.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: 'fleetengine.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.create_vehicle: gapic_v1.method.wrap_method( - self.create_vehicle, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.get_vehicle: gapic_v1.method.wrap_method( - self.get_vehicle, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_vehicle: gapic_v1.method.wrap_method( - self.update_vehicle, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_vehicle_attributes: gapic_v1.method.wrap_method( - self.update_vehicle_attributes, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.list_vehicles: gapic_v1.method.wrap_method( - self.list_vehicles, - default_timeout=None, - client_info=client_info, - ), - self.search_vehicles: gapic_v1.method.wrap_method( - self.search_vehicles, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - 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 create_vehicle(self) -> Callable[ - [vehicle_api.CreateVehicleRequest], - Union[ - vehicles.Vehicle, - Awaitable[vehicles.Vehicle] - ]]: - raise NotImplementedError() - - @property - def get_vehicle(self) -> Callable[ - [vehicle_api.GetVehicleRequest], - Union[ - vehicles.Vehicle, - Awaitable[vehicles.Vehicle] - ]]: - raise NotImplementedError() - - @property - def update_vehicle(self) -> Callable[ - [vehicle_api.UpdateVehicleRequest], - Union[ - vehicles.Vehicle, - Awaitable[vehicles.Vehicle] - ]]: - raise NotImplementedError() - - @property - def update_vehicle_attributes(self) -> Callable[ - [vehicle_api.UpdateVehicleAttributesRequest], - Union[ - vehicle_api.UpdateVehicleAttributesResponse, - Awaitable[vehicle_api.UpdateVehicleAttributesResponse] - ]]: - raise NotImplementedError() - - @property - def list_vehicles(self) -> Callable[ - [vehicle_api.ListVehiclesRequest], - Union[ - vehicle_api.ListVehiclesResponse, - Awaitable[vehicle_api.ListVehiclesResponse] - ]]: - raise NotImplementedError() - - @property - def search_vehicles(self) -> Callable[ - [vehicle_api.SearchVehiclesRequest], - Union[ - vehicle_api.SearchVehiclesResponse, - Awaitable[vehicle_api.SearchVehiclesResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'VehicleServiceTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py deleted file mode 100644 index 827cc20bd1dd..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py +++ /dev/null @@ -1,455 +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.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles -from .base import VehicleServiceTransport, DEFAULT_CLIENT_INFO - - -class VehicleServiceGrpcTransport(VehicleServiceTransport): - """gRPC backend transport for VehicleService. - - Vehicle management service. - - 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 = 'fleetengine.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: 'fleetengine.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 = 'fleetengine.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 create_vehicle(self) -> Callable[ - [vehicle_api.CreateVehicleRequest], - vehicles.Vehicle]: - r"""Return a callable for the create vehicle method over gRPC. - - Instantiates a new vehicle associated with an on-demand - rideshare or deliveries provider. Each ``Vehicle`` must have a - unique vehicle ID. - - The following ``Vehicle`` fields are required when creating a - ``Vehicle``: - - - ``vehicleState`` - - ``supportedTripTypes`` - - ``maximumCapacity`` - - ``vehicleType`` - - The following ``Vehicle`` fields are ignored when creating a - ``Vehicle``: - - - ``name`` - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_version`` - - ``current_route_segment_traffic`` - - ``route`` - - ``waypoints`` - - ``waypoints_version`` - - ``remaining_distance_meters`` - - ``remaining_time_seconds`` - - ``eta_to_next_waypoint`` - - ``navigation_status`` - - All other fields are optional and used if provided. - - Returns: - Callable[[~.CreateVehicleRequest], - ~.Vehicle]: - 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 'create_vehicle' not in self._stubs: - self._stubs['create_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/CreateVehicle', - request_serializer=vehicle_api.CreateVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['create_vehicle'] - - @property - def get_vehicle(self) -> Callable[ - [vehicle_api.GetVehicleRequest], - vehicles.Vehicle]: - r"""Return a callable for the get vehicle method over gRPC. - - Returns a vehicle from the Fleet Engine. - - Returns: - Callable[[~.GetVehicleRequest], - ~.Vehicle]: - 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 'get_vehicle' not in self._stubs: - self._stubs['get_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/GetVehicle', - request_serializer=vehicle_api.GetVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['get_vehicle'] - - @property - def update_vehicle(self) -> Callable[ - [vehicle_api.UpdateVehicleRequest], - vehicles.Vehicle]: - r"""Return a callable for the update vehicle method over gRPC. - - Writes updated vehicle data to the Fleet Engine. - - When updating a ``Vehicle``, the following fields cannot be - updated since they are managed by the server: - - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment_version`` - - ``waypoints_version`` - - The vehicle ``name`` also cannot be updated. - - If the ``attributes`` field is updated, **all** the vehicle's - attributes are replaced with the attributes provided in the - request. If you want to update only some attributes, see the - ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` - field can be updated, but must contain all the waypoints - currently on the vehicle, and no other waypoints. - - Returns: - Callable[[~.UpdateVehicleRequest], - ~.Vehicle]: - 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 'update_vehicle' not in self._stubs: - self._stubs['update_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/UpdateVehicle', - request_serializer=vehicle_api.UpdateVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['update_vehicle'] - - @property - def update_vehicle_attributes(self) -> Callable[ - [vehicle_api.UpdateVehicleAttributesRequest], - vehicle_api.UpdateVehicleAttributesResponse]: - r"""Return a callable for the update vehicle attributes method over gRPC. - - Partially updates a vehicle's attributes. Only the attributes - mentioned in the request will be updated, other attributes will - NOT be altered. Note: this is different in ``UpdateVehicle``, - where the whole ``attributes`` field will be replaced by the one - in ``UpdateVehicleRequest``, attributes not in the request would - be removed. - - Returns: - Callable[[~.UpdateVehicleAttributesRequest], - ~.UpdateVehicleAttributesResponse]: - 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 'update_vehicle_attributes' not in self._stubs: - self._stubs['update_vehicle_attributes'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/UpdateVehicleAttributes', - request_serializer=vehicle_api.UpdateVehicleAttributesRequest.serialize, - response_deserializer=vehicle_api.UpdateVehicleAttributesResponse.deserialize, - ) - return self._stubs['update_vehicle_attributes'] - - @property - def list_vehicles(self) -> Callable[ - [vehicle_api.ListVehiclesRequest], - vehicle_api.ListVehiclesResponse]: - r"""Return a callable for the list vehicles method over gRPC. - - Returns a paginated list of vehicles associated with - a provider that match the request options. - - Returns: - Callable[[~.ListVehiclesRequest], - ~.ListVehiclesResponse]: - 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 'list_vehicles' not in self._stubs: - self._stubs['list_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/ListVehicles', - request_serializer=vehicle_api.ListVehiclesRequest.serialize, - response_deserializer=vehicle_api.ListVehiclesResponse.deserialize, - ) - return self._stubs['list_vehicles'] - - @property - def search_vehicles(self) -> Callable[ - [vehicle_api.SearchVehiclesRequest], - vehicle_api.SearchVehiclesResponse]: - r"""Return a callable for the search vehicles method over gRPC. - - Returns a list of vehicles that match the request - options. - - Returns: - Callable[[~.SearchVehiclesRequest], - ~.SearchVehiclesResponse]: - 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 'search_vehicles' not in self._stubs: - self._stubs['search_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/SearchVehicles', - request_serializer=vehicle_api.SearchVehiclesRequest.serialize, - response_deserializer=vehicle_api.SearchVehiclesResponse.deserialize, - ) - return self._stubs['search_vehicles'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'VehicleServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py deleted file mode 100644 index 952dd0c816f8..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,546 +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.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles -from .base import VehicleServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import VehicleServiceGrpcTransport - - -class VehicleServiceGrpcAsyncIOTransport(VehicleServiceTransport): - """gRPC AsyncIO backend transport for VehicleService. - - Vehicle management service. - - 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 = 'fleetengine.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 = 'fleetengine.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: 'fleetengine.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 create_vehicle(self) -> Callable[ - [vehicle_api.CreateVehicleRequest], - Awaitable[vehicles.Vehicle]]: - r"""Return a callable for the create vehicle method over gRPC. - - Instantiates a new vehicle associated with an on-demand - rideshare or deliveries provider. Each ``Vehicle`` must have a - unique vehicle ID. - - The following ``Vehicle`` fields are required when creating a - ``Vehicle``: - - - ``vehicleState`` - - ``supportedTripTypes`` - - ``maximumCapacity`` - - ``vehicleType`` - - The following ``Vehicle`` fields are ignored when creating a - ``Vehicle``: - - - ``name`` - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_version`` - - ``current_route_segment_traffic`` - - ``route`` - - ``waypoints`` - - ``waypoints_version`` - - ``remaining_distance_meters`` - - ``remaining_time_seconds`` - - ``eta_to_next_waypoint`` - - ``navigation_status`` - - All other fields are optional and used if provided. - - Returns: - Callable[[~.CreateVehicleRequest], - Awaitable[~.Vehicle]]: - 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 'create_vehicle' not in self._stubs: - self._stubs['create_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/CreateVehicle', - request_serializer=vehicle_api.CreateVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['create_vehicle'] - - @property - def get_vehicle(self) -> Callable[ - [vehicle_api.GetVehicleRequest], - Awaitable[vehicles.Vehicle]]: - r"""Return a callable for the get vehicle method over gRPC. - - Returns a vehicle from the Fleet Engine. - - Returns: - Callable[[~.GetVehicleRequest], - Awaitable[~.Vehicle]]: - 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 'get_vehicle' not in self._stubs: - self._stubs['get_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/GetVehicle', - request_serializer=vehicle_api.GetVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['get_vehicle'] - - @property - def update_vehicle(self) -> Callable[ - [vehicle_api.UpdateVehicleRequest], - Awaitable[vehicles.Vehicle]]: - r"""Return a callable for the update vehicle method over gRPC. - - Writes updated vehicle data to the Fleet Engine. - - When updating a ``Vehicle``, the following fields cannot be - updated since they are managed by the server: - - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment_version`` - - ``waypoints_version`` - - The vehicle ``name`` also cannot be updated. - - If the ``attributes`` field is updated, **all** the vehicle's - attributes are replaced with the attributes provided in the - request. If you want to update only some attributes, see the - ``UpdateVehicleAttributes`` method. Likewise, the ``waypoints`` - field can be updated, but must contain all the waypoints - currently on the vehicle, and no other waypoints. - - Returns: - Callable[[~.UpdateVehicleRequest], - Awaitable[~.Vehicle]]: - 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 'update_vehicle' not in self._stubs: - self._stubs['update_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/UpdateVehicle', - request_serializer=vehicle_api.UpdateVehicleRequest.serialize, - response_deserializer=vehicles.Vehicle.deserialize, - ) - return self._stubs['update_vehicle'] - - @property - def update_vehicle_attributes(self) -> Callable[ - [vehicle_api.UpdateVehicleAttributesRequest], - Awaitable[vehicle_api.UpdateVehicleAttributesResponse]]: - r"""Return a callable for the update vehicle attributes method over gRPC. - - Partially updates a vehicle's attributes. Only the attributes - mentioned in the request will be updated, other attributes will - NOT be altered. Note: this is different in ``UpdateVehicle``, - where the whole ``attributes`` field will be replaced by the one - in ``UpdateVehicleRequest``, attributes not in the request would - be removed. - - Returns: - Callable[[~.UpdateVehicleAttributesRequest], - Awaitable[~.UpdateVehicleAttributesResponse]]: - 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 'update_vehicle_attributes' not in self._stubs: - self._stubs['update_vehicle_attributes'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/UpdateVehicleAttributes', - request_serializer=vehicle_api.UpdateVehicleAttributesRequest.serialize, - response_deserializer=vehicle_api.UpdateVehicleAttributesResponse.deserialize, - ) - return self._stubs['update_vehicle_attributes'] - - @property - def list_vehicles(self) -> Callable[ - [vehicle_api.ListVehiclesRequest], - Awaitable[vehicle_api.ListVehiclesResponse]]: - r"""Return a callable for the list vehicles method over gRPC. - - Returns a paginated list of vehicles associated with - a provider that match the request options. - - Returns: - Callable[[~.ListVehiclesRequest], - Awaitable[~.ListVehiclesResponse]]: - 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 'list_vehicles' not in self._stubs: - self._stubs['list_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/ListVehicles', - request_serializer=vehicle_api.ListVehiclesRequest.serialize, - response_deserializer=vehicle_api.ListVehiclesResponse.deserialize, - ) - return self._stubs['list_vehicles'] - - @property - def search_vehicles(self) -> Callable[ - [vehicle_api.SearchVehiclesRequest], - Awaitable[vehicle_api.SearchVehiclesResponse]]: - r"""Return a callable for the search vehicles method over gRPC. - - Returns a list of vehicles that match the request - options. - - Returns: - Callable[[~.SearchVehiclesRequest], - Awaitable[~.SearchVehiclesResponse]]: - 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 'search_vehicles' not in self._stubs: - self._stubs['search_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.v1.VehicleService/SearchVehicles', - request_serializer=vehicle_api.SearchVehiclesRequest.serialize, - response_deserializer=vehicle_api.SearchVehiclesResponse.deserialize, - ) - return self._stubs['search_vehicles'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.create_vehicle: self._wrap_method( - self.create_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.get_vehicle: self._wrap_method( - self.get_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_vehicle: self._wrap_method( - self.update_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.update_vehicle_attributes: self._wrap_method( - self.update_vehicle_attributes, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.list_vehicles: self._wrap_method( - self.list_vehicles, - default_timeout=None, - client_info=client_info, - ), - self.search_vehicles: self._wrap_method( - self.search_vehicles, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - 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__ = ( - 'VehicleServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py deleted file mode 100644 index cba18024bd88..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/__init__.py +++ /dev/null @@ -1,124 +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 .fleetengine import ( - TerminalLocation, - TerminalPointId, - TripWaypoint, - VehicleAttribute, - VehicleLocation, - LocationSensor, - NavigationStatus, - PolylineFormatType, - TripType, - WaypointType, -) -from .header import ( - RequestHeader, -) -from .traffic import ( - ConsumableTrafficPolyline, - SpeedReadingInterval, -) -from .trip_api import ( - CreateTripRequest, - GetTripRequest, - ReportBillableTripRequest, - SearchTripsRequest, - SearchTripsResponse, - UpdateTripRequest, -) -from .trips import ( - StopLocation, - Trip, - BillingPlatformIdentifier, - TripStatus, - TripView, -) -from .vehicle_api import ( - CreateVehicleRequest, - GetVehicleRequest, - ListVehiclesRequest, - ListVehiclesResponse, - SearchVehiclesRequest, - SearchVehiclesResponse, - UpdateVehicleAttributesRequest, - UpdateVehicleAttributesResponse, - UpdateVehicleRequest, - VehicleAttributeList, - VehicleMatch, - Waypoint, -) -from .vehicles import ( - BatteryInfo, - DeviceSettings, - LicensePlate, - TrafficPolylineData, - Vehicle, - VisualTrafficReportPolylineRendering, - BatteryStatus, - LocationPowerSaveMode, - PowerSource, - VehicleState, -) - -__all__ = ( - 'TerminalLocation', - 'TerminalPointId', - 'TripWaypoint', - 'VehicleAttribute', - 'VehicleLocation', - 'LocationSensor', - 'NavigationStatus', - 'PolylineFormatType', - 'TripType', - 'WaypointType', - 'RequestHeader', - 'ConsumableTrafficPolyline', - 'SpeedReadingInterval', - 'CreateTripRequest', - 'GetTripRequest', - 'ReportBillableTripRequest', - 'SearchTripsRequest', - 'SearchTripsResponse', - 'UpdateTripRequest', - 'StopLocation', - 'Trip', - 'BillingPlatformIdentifier', - 'TripStatus', - 'TripView', - 'CreateVehicleRequest', - 'GetVehicleRequest', - 'ListVehiclesRequest', - 'ListVehiclesResponse', - 'SearchVehiclesRequest', - 'SearchVehiclesResponse', - 'UpdateVehicleAttributesRequest', - 'UpdateVehicleAttributesResponse', - 'UpdateVehicleRequest', - 'VehicleAttributeList', - 'VehicleMatch', - 'Waypoint', - 'BatteryInfo', - 'DeviceSettings', - 'LicensePlate', - 'TrafficPolylineData', - 'Vehicle', - 'VisualTrafficReportPolylineRendering', - 'BatteryStatus', - 'LocationPowerSaveMode', - 'PowerSource', - 'VehicleState', -) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py deleted file mode 100644 index 95fe3f592984..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/fleetengine.py +++ /dev/null @@ -1,628 +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.fleetengine_v1.types import traffic -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.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'TripType', - 'WaypointType', - 'PolylineFormatType', - 'NavigationStatus', - 'LocationSensor', - 'TerminalPointId', - 'TerminalLocation', - 'TripWaypoint', - 'VehicleAttribute', - 'VehicleLocation', - }, -) - - -class TripType(proto.Enum): - r"""The type of a trip. - - Values: - UNKNOWN_TRIP_TYPE (0): - Default, used for unspecified or unrecognized - trip types. - SHARED (1): - The trip may share a vehicle with other - trips. - EXCLUSIVE (2): - The trip is exclusive to a vehicle. - """ - UNKNOWN_TRIP_TYPE = 0 - SHARED = 1 - EXCLUSIVE = 2 - - -class WaypointType(proto.Enum): - r"""The type of waypoint. - - Values: - UNKNOWN_WAYPOINT_TYPE (0): - Unknown or unspecified waypoint type. - PICKUP_WAYPOINT_TYPE (1): - Waypoints for picking up riders or items. - DROP_OFF_WAYPOINT_TYPE (2): - Waypoints for dropping off riders or items. - INTERMEDIATE_DESTINATION_WAYPOINT_TYPE (3): - Waypoints for intermediate destinations in a - multi-destination trip. - """ - UNKNOWN_WAYPOINT_TYPE = 0 - PICKUP_WAYPOINT_TYPE = 1 - DROP_OFF_WAYPOINT_TYPE = 2 - INTERMEDIATE_DESTINATION_WAYPOINT_TYPE = 3 - - -class PolylineFormatType(proto.Enum): - r"""The type of polyline format. - - Values: - UNKNOWN_FORMAT_TYPE (0): - The format is unspecified or unknown. - LAT_LNG_LIST_TYPE (1): - A list of ``google.type.LatLng``. - ENCODED_POLYLINE_TYPE (2): - A polyline encoded with a polyline - compression algorithm. Decoding is not yet - supported. - """ - UNKNOWN_FORMAT_TYPE = 0 - LAT_LNG_LIST_TYPE = 1 - ENCODED_POLYLINE_TYPE = 2 - - -class NavigationStatus(proto.Enum): - r"""The vehicle's navigation status. - - Values: - UNKNOWN_NAVIGATION_STATUS (0): - Unspecified navigation status. - NO_GUIDANCE (1): - The Driver app's navigation is in ``FREE_NAV`` mode. - ENROUTE_TO_DESTINATION (2): - Turn-by-turn navigation is available and the Driver app - navigation has entered ``GUIDED_NAV`` mode. - OFF_ROUTE (3): - The vehicle has gone off the suggested route. - ARRIVED_AT_DESTINATION (4): - The vehicle is within approximately 50m of - the destination. - """ - UNKNOWN_NAVIGATION_STATUS = 0 - NO_GUIDANCE = 1 - ENROUTE_TO_DESTINATION = 2 - OFF_ROUTE = 3 - ARRIVED_AT_DESTINATION = 4 - - -class LocationSensor(proto.Enum): - r"""The sensor or methodology used to determine the location. - - Values: - UNKNOWN_SENSOR (0): - The sensor is unspecified or unknown. - GPS (1): - GPS or Assisted GPS. - NETWORK (2): - Assisted GPS, cell tower ID, or WiFi access - point. - PASSIVE (3): - Cell tower ID or WiFi access point. - ROAD_SNAPPED_LOCATION_PROVIDER (4): - A location determined by the mobile device to - be the most likely road position. - CUSTOMER_SUPPLIED_LOCATION (5): - A customer-supplied location from an independent source. - Typically, this value is used for a location provided from - sources other than the mobile device running Driver SDK. If - the original source is described by one of the other enum - values, use that value. Locations marked - CUSTOMER_SUPPLIED_LOCATION are typically provided via a - Vehicle's ``last_location.supplemental_location_sensor``. - FLEET_ENGINE_LOCATION (6): - A location calculated by Fleet Engine based - on the signals available to it. Output only. - This value will be rejected if it is received in - a request. - FUSED_LOCATION_PROVIDER (100): - Android's Fused Location Provider. - CORE_LOCATION (200): - The location provider on Apple operating - systems. - """ - UNKNOWN_SENSOR = 0 - GPS = 1 - NETWORK = 2 - PASSIVE = 3 - ROAD_SNAPPED_LOCATION_PROVIDER = 4 - CUSTOMER_SUPPLIED_LOCATION = 5 - FLEET_ENGINE_LOCATION = 6 - FUSED_LOCATION_PROVIDER = 100 - CORE_LOCATION = 200 - - -class TerminalPointId(proto.Message): - r"""Deprecated: TerminalPoints are no longer supported in Fleet Engine. - Use ``TerminalLocation.point`` instead. - - 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: - place_id (str): - Deprecated. - - This field is a member of `oneof`_ ``Id``. - generated_id (str): - Deprecated. - - This field is a member of `oneof`_ ``Id``. - value (str): - Deprecated. - """ - - place_id: str = proto.Field( - proto.STRING, - number=2, - oneof='Id', - ) - generated_id: str = proto.Field( - proto.STRING, - number=3, - oneof='Id', - ) - value: str = proto.Field( - proto.STRING, - number=4, - ) - - -class TerminalLocation(proto.Message): - r"""Describes the location of a waypoint. - - Attributes: - point (google.type.latlng_pb2.LatLng): - Required. Denotes the location of a trip - waypoint. - terminal_point_id (google.maps.fleetengine_v1.types.TerminalPointId): - Deprecated: Specify the ``point`` field instead. - access_point_id (str): - Deprecated: Specify the ``point`` field instead. - trip_id (str): - Deprecated. - terminal_location_type (google.maps.fleetengine_v1.types.WaypointType): - Deprecated: ``Vehicle.waypoint`` will have this data. - """ - - point: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - terminal_point_id: 'TerminalPointId' = proto.Field( - proto.MESSAGE, - number=2, - message='TerminalPointId', - ) - access_point_id: str = proto.Field( - proto.STRING, - number=3, - ) - trip_id: str = proto.Field( - proto.STRING, - number=4, - ) - terminal_location_type: 'WaypointType' = proto.Field( - proto.ENUM, - number=5, - enum='WaypointType', - ) - - -class TripWaypoint(proto.Message): - r"""Describes a stopping point on a vehicle's route or an ending - point on a vehicle's trip. - - Attributes: - location (google.maps.fleetengine_v1.types.TerminalLocation): - The location of this waypoint. - trip_id (str): - The trip associated with this waypoint. - waypoint_type (google.maps.fleetengine_v1.types.WaypointType): - The role this waypoint plays in this trip, - such as pickup or dropoff. - path_to_waypoint (MutableSequence[google.type.latlng_pb2.LatLng]): - The path from the previous waypoint to the - current waypoint. Undefined for the first - waypoint in a list. This field is only populated - when requested. - encoded_path_to_waypoint (str): - The encoded path from the previous waypoint - to the current waypoint. -

Note: This field is intended only for use by - the Driver SDK and Consumer SDK. Decoding is not - yet supported. - traffic_to_waypoint (google.maps.fleetengine_v1.types.ConsumableTrafficPolyline): - The traffic conditions along the path to this - waypoint. Note that traffic is only available - for Google Map Platform Rides and Deliveries - Solution customers. - distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The path distance from the previous waypoint - to the current waypoint. Undefined for the first - waypoint in a list. - eta (google.protobuf.timestamp_pb2.Timestamp): - The estimated time of arrival at this - waypoint. Undefined for the first waypoint in a - list. - duration (google.protobuf.duration_pb2.Duration): - The travel time from previous waypoint to - this point. Undefined for the first waypoint in - a list. - """ - - location: 'TerminalLocation' = proto.Field( - proto.MESSAGE, - number=1, - message='TerminalLocation', - ) - trip_id: str = proto.Field( - proto.STRING, - number=2, - ) - waypoint_type: 'WaypointType' = proto.Field( - proto.ENUM, - number=3, - enum='WaypointType', - ) - path_to_waypoint: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=latlng_pb2.LatLng, - ) - encoded_path_to_waypoint: str = proto.Field( - proto.STRING, - number=5, - ) - traffic_to_waypoint: traffic.ConsumableTrafficPolyline = proto.Field( - proto.MESSAGE, - number=10, - message=traffic.ConsumableTrafficPolyline, - ) - distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.Int32Value, - ) - eta: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - - -class VehicleAttribute(proto.Message): - r"""Describes a vehicle attribute as a key-value pair. The - "key:value" string length cannot exceed 256 characters. - - 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: - key (str): - The attribute's key. Keys may not contain the - colon character (:). - value (str): - The attribute's value. - string_value (str): - String typed attribute value. - - Note: This is identical to the ``value`` field which will - eventually be deprecated. For create or update methods, - either field can be used, but it's strongly recommended to - use ``string_value``. If both ``string_value`` and ``value`` - are set, they must be identical or an error will be thrown. - Both fields are populated in responses. - - This field is a member of `oneof`_ ``vehicle_attribute_value``. - bool_value (bool): - Boolean typed attribute value. - - This field is a member of `oneof`_ ``vehicle_attribute_value``. - number_value (float): - Double typed attribute value. - - This field is a member of `oneof`_ ``vehicle_attribute_value``. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - string_value: str = proto.Field( - proto.STRING, - number=3, - oneof='vehicle_attribute_value', - ) - bool_value: bool = proto.Field( - proto.BOOL, - number=4, - oneof='vehicle_attribute_value', - ) - number_value: float = proto.Field( - proto.DOUBLE, - number=5, - oneof='vehicle_attribute_value', - ) - - -class VehicleLocation(proto.Message): - r"""The location, speed, and heading of a vehicle at a point in - time. - - Attributes: - location (google.type.latlng_pb2.LatLng): - The location of the vehicle. When it is sent to Fleet - Engine, the vehicle's location is a GPS location. When you - receive it in a response, the vehicle's location can be - either a GPS location, a supplemental location, or some - other estimated location. The source is specified in - ``location_sensor``. - horizontal_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Deprecated: Use ``latlng_accuracy`` instead. - latlng_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``location`` in meters as a radius. - heading (google.protobuf.wrappers_pb2.Int32Value): - Direction the vehicle is moving in degrees. 0 represents - North. The valid range is [0,360). - bearing_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Deprecated: Use ``heading_accuracy`` instead. - heading_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``heading`` in degrees. - altitude (google.protobuf.wrappers_pb2.DoubleValue): - Altitude in meters above WGS84. - vertical_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Deprecated: Use ``altitude_accuracy`` instead. - altitude_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``altitude`` in meters. - speed_kmph (google.protobuf.wrappers_pb2.Int32Value): - Speed of the vehicle in kilometers per hour. Deprecated: Use - ``speed`` instead. - speed (google.protobuf.wrappers_pb2.DoubleValue): - Speed of the vehicle in meters/second - speed_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``speed`` in meters/second. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time when ``location`` was reported by the sensor - according to the sensor's clock. - server_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the server - received the location information. - location_sensor (google.maps.fleetengine_v1.types.LocationSensor): - Provider of location data (for example, ``GPS``). - is_road_snapped (google.protobuf.wrappers_pb2.BoolValue): - Whether ``location`` is snapped to a road. - is_gps_sensor_enabled (google.protobuf.wrappers_pb2.BoolValue): - Input only. Indicates whether the GPS sensor - is enabled on the mobile device. - time_since_update (google.protobuf.wrappers_pb2.Int32Value): - Input only. Time (in seconds) since this - location was first sent to the server. This will - be zero for the first update. If the time is - unknown (for example, when the app restarts), - this value resets to zero. - num_stale_updates (google.protobuf.wrappers_pb2.Int32Value): - Input only. Deprecated: Other signals are now - used to determine if a location is stale. - raw_location (google.type.latlng_pb2.LatLng): - Raw vehicle location (unprocessed by - road-snapper). - raw_location_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp associated with the raw location. - raw_location_sensor (google.maps.fleetengine_v1.types.LocationSensor): - Source of the raw location. Defaults to ``GPS``. - raw_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``raw_location`` as a radius, in meters. - supplemental_location (google.type.latlng_pb2.LatLng): - Supplemental location provided by the - integrating app. - supplemental_location_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp associated with the supplemental - location. - supplemental_location_sensor (google.maps.fleetengine_v1.types.LocationSensor): - Source of the supplemental location. Defaults to - ``CUSTOMER_SUPPLIED_LOCATION``. - supplemental_location_accuracy (google.protobuf.wrappers_pb2.DoubleValue): - Accuracy of ``supplemental_location`` as a radius, in - meters. - road_snapped (bool): - Deprecated: Use ``is_road_snapped`` instead. - """ - - location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - horizontal_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=8, - message=wrappers_pb2.DoubleValue, - ) - latlng_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=22, - message=wrappers_pb2.DoubleValue, - ) - heading: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - bearing_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=10, - message=wrappers_pb2.DoubleValue, - ) - heading_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=23, - message=wrappers_pb2.DoubleValue, - ) - altitude: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.DoubleValue, - ) - vertical_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=9, - message=wrappers_pb2.DoubleValue, - ) - altitude_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=24, - message=wrappers_pb2.DoubleValue, - ) - speed_kmph: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int32Value, - ) - speed: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.DoubleValue, - ) - speed_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=7, - message=wrappers_pb2.DoubleValue, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - server_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=13, - message=timestamp_pb2.Timestamp, - ) - location_sensor: 'LocationSensor' = proto.Field( - proto.ENUM, - number=11, - enum='LocationSensor', - ) - is_road_snapped: wrappers_pb2.BoolValue = proto.Field( - proto.MESSAGE, - number=27, - message=wrappers_pb2.BoolValue, - ) - is_gps_sensor_enabled: wrappers_pb2.BoolValue = proto.Field( - proto.MESSAGE, - number=12, - message=wrappers_pb2.BoolValue, - ) - time_since_update: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=14, - message=wrappers_pb2.Int32Value, - ) - num_stale_updates: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=15, - message=wrappers_pb2.Int32Value, - ) - raw_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=16, - message=latlng_pb2.LatLng, - ) - raw_location_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=17, - message=timestamp_pb2.Timestamp, - ) - raw_location_sensor: 'LocationSensor' = proto.Field( - proto.ENUM, - number=28, - enum='LocationSensor', - ) - raw_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=25, - message=wrappers_pb2.DoubleValue, - ) - supplemental_location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=18, - message=latlng_pb2.LatLng, - ) - supplemental_location_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - message=timestamp_pb2.Timestamp, - ) - supplemental_location_sensor: 'LocationSensor' = proto.Field( - proto.ENUM, - number=20, - enum='LocationSensor', - ) - supplemental_location_accuracy: wrappers_pb2.DoubleValue = proto.Field( - proto.MESSAGE, - number=21, - message=wrappers_pb2.DoubleValue, - ) - road_snapped: bool = proto.Field( - proto.BOOL, - number=26, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py deleted file mode 100644 index 6cc60e782c23..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/header.py +++ /dev/null @@ -1,168 +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='maps.fleetengine.v1', - manifest={ - 'RequestHeader', - }, -) - - -class RequestHeader(proto.Message): - r"""A RequestHeader contains fields common to all Fleet Engine - RPC requests. - - Attributes: - language_code (str): - The BCP-47 language code, such as en-US or sr-Latn. For more - information, see - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. - If none is specified, the response may be in any language, - with a preference for English if such a name exists. Field - value example: ``en-US``. - region_code (str): - Required. CLDR region code of the region where the request - originates. Field value example: ``US``. - sdk_version (str): - Version of the calling SDK, if applicable. The version - format is "major.minor.patch", example: ``1.1.2``. - os_version (str): - Version of the operating system on which the calling SDK is - running. Field value examples: ``4.4.1``, ``12.1``. - device_model (str): - Model of the device on which the calling SDK is running. - Field value examples: ``iPhone12,1``, ``SM-G920F``. - sdk_type (google.maps.fleetengine_v1.types.RequestHeader.SdkType): - The type of SDK sending the request. - maps_sdk_version (str): - Version of the MapSDK which the calling SDK depends on, if - applicable. The version format is "major.minor.patch", - example: ``5.2.1``. - nav_sdk_version (str): - Version of the NavSDK which the calling SDK depends on, if - applicable. The version format is "major.minor.patch", - example: ``2.1.0``. - platform (google.maps.fleetengine_v1.types.RequestHeader.Platform): - Platform of the calling SDK. - manufacturer (str): - Manufacturer of the Android device from the calling SDK, - only applicable for the Android SDKs. Field value example: - ``Samsung``. - android_api_level (int): - Android API level of the calling SDK, only applicable for - the Android SDKs. Field value example: ``23``. - trace_id (str): - Optional ID that can be provided for logging - purposes in order to identify the request. - """ - class SdkType(proto.Enum): - r"""Possible types of SDK. - - Values: - SDK_TYPE_UNSPECIFIED (0): - The default value. This value is used if the ``sdk_type`` is - omitted. - CONSUMER (1): - The calling SDK is Consumer. - DRIVER (2): - The calling SDK is Driver. - JAVASCRIPT (3): - The calling SDK is JavaScript. - """ - SDK_TYPE_UNSPECIFIED = 0 - CONSUMER = 1 - DRIVER = 2 - JAVASCRIPT = 3 - - class Platform(proto.Enum): - r"""The platform of the calling SDK. - - Values: - PLATFORM_UNSPECIFIED (0): - The default value. This value is used if the - platform is omitted. - ANDROID (1): - The request is coming from Android. - IOS (2): - The request is coming from iOS. - WEB (3): - The request is coming from the web. - """ - PLATFORM_UNSPECIFIED = 0 - ANDROID = 1 - IOS = 2 - WEB = 3 - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - region_code: str = proto.Field( - proto.STRING, - number=2, - ) - sdk_version: str = proto.Field( - proto.STRING, - number=3, - ) - os_version: str = proto.Field( - proto.STRING, - number=4, - ) - device_model: str = proto.Field( - proto.STRING, - number=5, - ) - sdk_type: SdkType = proto.Field( - proto.ENUM, - number=6, - enum=SdkType, - ) - maps_sdk_version: str = proto.Field( - proto.STRING, - number=7, - ) - nav_sdk_version: str = proto.Field( - proto.STRING, - number=8, - ) - platform: Platform = proto.Field( - proto.ENUM, - number=9, - enum=Platform, - ) - manufacturer: str = proto.Field( - proto.STRING, - number=10, - ) - android_api_level: int = proto.Field( - proto.INT32, - number=11, - ) - trace_id: str = proto.Field( - proto.STRING, - number=12, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py deleted file mode 100644 index c67d29281d61..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/traffic.py +++ /dev/null @@ -1,108 +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='maps.fleetengine.v1', - manifest={ - 'SpeedReadingInterval', - 'ConsumableTrafficPolyline', - }, -) - - -class SpeedReadingInterval(proto.Message): - r"""Traffic density indicator on a contiguous segment of a 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. - - Attributes: - start_polyline_point_index (int): - The starting index of this interval in the - path. In JSON, when the index is 0, the field - will appear to be unpopulated. - end_polyline_point_index (int): - The ending index of this interval in the - path. In JSON, when the index is 0, the field - will appear to be unpopulated. - speed (google.maps.fleetengine_v1.types.SpeedReadingInterval.Speed): - Traffic speed in this interval. - """ - class Speed(proto.Enum): - r"""The classification of polyline speed based on traffic data. - - Values: - SPEED_UNSPECIFIED (0): - Default value. This value is unused. - NORMAL (1): - Normal speed, no slowdown is detected. - SLOW (2): - Slowdown detected, but no traffic jam formed. - TRAFFIC_JAM (3): - Traffic jam detected. - """ - SPEED_UNSPECIFIED = 0 - NORMAL = 1 - SLOW = 2 - TRAFFIC_JAM = 3 - - start_polyline_point_index: int = proto.Field( - proto.INT32, - number=1, - ) - end_polyline_point_index: int = proto.Field( - proto.INT32, - number=2, - ) - speed: Speed = proto.Field( - proto.ENUM, - number=3, - enum=Speed, - ) - - -class ConsumableTrafficPolyline(proto.Message): - r"""Traffic density along a Vehicle's path. - - Attributes: - speed_reading_interval (MutableSequence[google.maps.fleetengine_v1.types.SpeedReadingInterval]): - Traffic speed along the path from the - previous waypoint to the current waypoint. - encoded_path_to_waypoint (str): - The path the driver is taking from the previous waypoint to - the current waypoint. This path has landmarks in it so - clients can show traffic markers along the path (see - ``speed_reading_interval``). Decoding is not yet supported. - """ - - speed_reading_interval: MutableSequence['SpeedReadingInterval'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SpeedReadingInterval', - ) - encoded_path_to_waypoint: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.py deleted file mode 100644 index 911a0a2053c2..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trip_api.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import header as mf_header -from google.maps.fleetengine_v1.types import trips as mf_trips -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'CreateTripRequest', - 'GetTripRequest', - 'ReportBillableTripRequest', - 'UpdateTripRequest', - 'SearchTripsRequest', - 'SearchTripsResponse', - }, -) - - -class CreateTripRequest(proto.Message): - r"""CreateTrip request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - trip_id (str): - Required. Unique Trip ID. Subject to the following - restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form C] - (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII characters: - '/', ':', '?', ',', or '#'. - trip (google.maps.fleetengine_v1.types.Trip): - Required. Trip entity to create. - - When creating a Trip, the following fields are required: - - - ``trip_type`` - - ``pickup_point`` - - The following fields are used if you provide them: - - - ``number_of_passengers`` - - ``vehicle_id`` - - ``dropoff_point`` - - ``intermediate_destinations`` - - ``vehicle_waypoints`` - - All other Trip fields are ignored. For example, all trips - start with a ``trip_status`` of ``NEW`` even if you pass in - a ``trip_status`` of ``CANCELED`` in the creation request. - - Only ``EXCLUSIVE`` trips support - ``intermediate_destinations``. - - When ``vehicle_id`` is set for a shared trip, you must - supply the list of ``Trip.vehicle_waypoints`` to specify the - order of the remaining waypoints for the vehicle, otherwise - the waypoint order will be undetermined. - - When you specify ``Trip.vehicle_waypoints``, the list must - contain all the remaining waypoints of the vehicle's trips, - with no extra waypoints. You must order these waypoints such - that for a given trip, the pickup point is before - intermediate destinations, and all intermediate destinations - come before the drop-off point. An ``EXCLUSIVE`` trip's - waypoints must not interleave with any other trips. - - The ``trip_id``, ``waypoint_type`` and ``location`` fields - are used, and all other TripWaypoint fields in - ``vehicle_waypoints`` are ignored. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - trip_id: str = proto.Field( - proto.STRING, - number=5, - ) - trip: mf_trips.Trip = proto.Field( - proto.MESSAGE, - number=4, - message=mf_trips.Trip, - ) - - -class GetTripRequest(proto.Message): - r"""GetTrip request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - name (str): - Required. Must be in the format - ``providers/{provider}/trips/{trip}``. The provider must be - the Project ID (for example, ``sample-cloud-project``) of - the Google Cloud Project of which the service account making - this call is a member. - view (google.maps.fleetengine_v1.types.TripView): - The subset of Trip fields that should be - returned and their interpretation. - current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Trip.route`` or ``Trip.current_route_segment`` data are - retrieved. If route data are unchanged since this timestamp, - the route field is not set in the response. If a minimum is - unspecified, the route data are always retrieved. - remaining_waypoints_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Trip.remaining_waypoints`` are retrieved. If they are - unchanged since this timestamp, the ``remaining_waypoints`` - are not set in the response. If this field is unspecified, - ``remaining_waypoints`` is always retrieved. - route_format_type (google.maps.fleetengine_v1.types.PolylineFormatType): - The returned current route format, ``LAT_LNG_LIST_TYPE`` (in - ``Trip.route``), or ``ENCODED_POLYLINE_TYPE`` (in - ``Trip.current_route_segment``). The default is - ``LAT_LNG_LIST_TYPE``. - current_route_segment_traffic_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Trip.current_route_segment_traffic`` is retrieved. If - traffic data are unchanged since this timestamp, the - ``current_route_segment_traffic`` field is not set in the - response. If a minimum is unspecified, the traffic data are - always retrieved. Note that traffic is only available for - On-Demand Rides and Deliveries Solution customers. - remaining_waypoints_route_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Trip.remaining_waypoints.traffic_to_waypoint`` and - ``Trip.remaining_waypoints.path_to_waypoint`` data are - retrieved. If data are unchanged since this timestamp, the - fields above are not set in the response. If - ``remaining_waypoints_route_version`` is unspecified, - traffic and path are always retrieved. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - view: mf_trips.TripView = proto.Field( - proto.ENUM, - number=11, - enum=mf_trips.TripView, - ) - current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - remaining_waypoints_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - route_format_type: fleetengine.PolylineFormatType = proto.Field( - proto.ENUM, - number=8, - enum=fleetengine.PolylineFormatType, - ) - current_route_segment_traffic_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - remaining_waypoints_route_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -class ReportBillableTripRequest(proto.Message): - r"""ReportBillableTrip request message. - - Attributes: - name (str): - Required. Must be in the format - ``providers/{provider}/billableTrips/{billable_trip}``. The - provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - country_code (str): - Required. Two letter country code of the - country where the trip takes place. Price is - defined according to country code. - platform (google.maps.fleetengine_v1.types.BillingPlatformIdentifier): - The platform upon which the request was - issued. - related_ids (MutableSequence[str]): - The identifiers that are directly related to the trip being - reported. These are usually IDs (for example, session IDs) - of pre-booking operations done before the trip ID is - available. The number of ``related_ids`` is limited to 50. - solution_type (google.maps.fleetengine_v1.types.ReportBillableTripRequest.SolutionType): - The type of GMP product solution (for example, - ``ON_DEMAND_RIDESHARING_AND_DELIVERIES``) used for the - reported trip. - """ - class SolutionType(proto.Enum): - r"""Selector for different solution types of a reported trip. - - Values: - SOLUTION_TYPE_UNSPECIFIED (0): - The default value. For backwards-compatibility, the API will - use ``ON_DEMAND_RIDESHARING_AND_DELIVERIES`` by default - which is the first supported solution type. - ON_DEMAND_RIDESHARING_AND_DELIVERIES (1): - The solution is an on-demand ridesharing and - deliveries trip. - """ - SOLUTION_TYPE_UNSPECIFIED = 0 - ON_DEMAND_RIDESHARING_AND_DELIVERIES = 1 - - name: str = proto.Field( - proto.STRING, - number=2, - ) - country_code: str = proto.Field( - proto.STRING, - number=3, - ) - platform: mf_trips.BillingPlatformIdentifier = proto.Field( - proto.ENUM, - number=5, - enum=mf_trips.BillingPlatformIdentifier, - ) - related_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - solution_type: SolutionType = proto.Field( - proto.ENUM, - number=7, - enum=SolutionType, - ) - - -class UpdateTripRequest(proto.Message): - r"""UpdateTrip request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - name (str): - Required. Must be in the format - ``providers/{provider}/trips/{trip}``. The provider must be - the Project ID (for example, ``sample-consumer-project``) of - the Google Cloud Project of which the service account making - this call is a member. - trip (google.maps.fleetengine_v1.types.Trip): - Required. The Trip associated with the update. - - The following fields are maintained by the Fleet Engine. Do - not update them using Trip.update. - - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_traffic`` - - ``current_route_segment_traffic_version`` - - ``current_route_segment_version`` - - ``dropoff_time`` - - ``eta_to_next_waypoint`` - - ``intermediate_destinations_version`` - - ``last_location`` - - ``name`` - - ``number_of_passengers`` - - ``pickup_time`` - - ``remaining_distance_meters`` - - ``remaining_time_to_first_waypoint`` - - ``remaining_waypoints`` - - ``remaining_waypoints_version`` - - ``route`` - - When you update the ``Trip.vehicle_id`` for a shared trip, - you must supply the list of ``Trip.vehicle_waypoints`` to - specify the order of the remaining waypoints, otherwise the - order will be undetermined. - - When you specify ``Trip.vehicle_waypoints``, the list must - contain all the remaining waypoints of the vehicle's trips, - with no extra waypoints. You must order these waypoints such - that for a given trip, the pickup point is before - intermediate destinations, and all intermediate destinations - come before the drop-off point. An ``EXCLUSIVE`` trip's - waypoints must not interleave with any other trips. The - ``trip_id``, ``waypoint_type`` and ``location`` fields are - used, and all other TripWaypoint fields in - ``vehicle_waypoints`` are ignored. - - To avoid a race condition for trips with multiple - destinations, you should provide - ``Trip.intermediate_destinations_version`` when updating the - trip status to ``ENROUTE_TO_INTERMEDIATE_DESTINATION``. The - ``Trip.intermediate_destinations_version`` passed must be - consistent with Fleet Engine's version. If it isn't, the - request fails. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The field mask indicating which fields in Trip to - update. The ``update_mask`` must contain at least one field. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - trip: mf_trips.Trip = proto.Field( - proto.MESSAGE, - number=4, - message=mf_trips.Trip, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class SearchTripsRequest(proto.Message): - r"""SearchTrips request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - vehicle_id (str): - The vehicle associated with the trips in the request. If - unspecified, the returned trips do not contain: - - - ``current_route_segment`` - - ``remaining_waypoints`` - - ``remaining_distance_meters`` - - ``eta_to_first_waypoint`` - active_trips_only (bool): - If set to true, the response includes Trips - that influence a driver's route. - page_size (int): - If not set, the server decides the number of - results to return. - page_token (str): - Set this to a value previously returned in the - ``SearchTripsResponse`` to continue from previous results. - minimum_staleness (google.protobuf.duration_pb2.Duration): - If specified, returns the trips that have not been updated - after the time ``(current - minimum_staleness)``. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - vehicle_id: str = proto.Field( - proto.STRING, - number=4, - ) - active_trips_only: bool = proto.Field( - proto.BOOL, - number=5, - ) - page_size: int = proto.Field( - proto.INT32, - number=6, - ) - page_token: str = proto.Field( - proto.STRING, - number=7, - ) - minimum_staleness: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - - -class SearchTripsResponse(proto.Message): - r"""SearchTrips response message. - - Attributes: - trips (MutableSequence[google.maps.fleetengine_v1.types.Trip]): - The list of trips for the requested vehicle. - next_page_token (str): - Pass this token in the SearchTripsRequest to - page through list results. The API returns a - trip list on each call, and when no more results - remain the trip list is empty. - """ - - @property - def raw_page(self): - return self - - trips: MutableSequence[mf_trips.Trip] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=mf_trips.Trip, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py deleted file mode 100644 index 7fd145d8cd69..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/trips.py +++ /dev/null @@ -1,490 +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.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import traffic -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.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'TripStatus', - 'BillingPlatformIdentifier', - 'TripView', - 'Trip', - 'StopLocation', - }, -) - - -class TripStatus(proto.Enum): - r"""The status of a trip indicating its progression. - - Values: - UNKNOWN_TRIP_STATUS (0): - Default, used for unspecified or unrecognized - trip status. - NEW (1): - Newly created trip. - ENROUTE_TO_PICKUP (2): - The driver is on their way to the pickup - point. - ARRIVED_AT_PICKUP (3): - The driver has arrived at the pickup point. - ARRIVED_AT_INTERMEDIATE_DESTINATION (7): - The driver has arrived at an intermediate - destination and is waiting for the rider. - ENROUTE_TO_INTERMEDIATE_DESTINATION (8): - The driver is on their way to an intermediate - destination (not the dropoff point). - ENROUTE_TO_DROPOFF (4): - The driver has picked up the rider and is on - their way to the next destination. - COMPLETE (5): - The rider has been dropped off and the trip - is complete. - CANCELED (6): - The trip was canceled prior to pickup by the - driver, rider, or rideshare provider. - """ - UNKNOWN_TRIP_STATUS = 0 - NEW = 1 - ENROUTE_TO_PICKUP = 2 - ARRIVED_AT_PICKUP = 3 - ARRIVED_AT_INTERMEDIATE_DESTINATION = 7 - ENROUTE_TO_INTERMEDIATE_DESTINATION = 8 - ENROUTE_TO_DROPOFF = 4 - COMPLETE = 5 - CANCELED = 6 - - -class BillingPlatformIdentifier(proto.Enum): - r"""A set of values that indicate upon which platform the request - was issued. - - Values: - BILLING_PLATFORM_IDENTIFIER_UNSPECIFIED (0): - Default. Used for unspecified platforms. - SERVER (1): - The platform is a client server. - WEB (2): - The platform is a web browser. - ANDROID (3): - The platform is an Android mobile device. - IOS (4): - The platform is an IOS mobile device. - OTHERS (5): - Other platforms that are not listed in this - enumeration. - """ - BILLING_PLATFORM_IDENTIFIER_UNSPECIFIED = 0 - SERVER = 1 - WEB = 2 - ANDROID = 3 - IOS = 4 - OTHERS = 5 - - -class TripView(proto.Enum): - r"""Selector for different sets of Trip fields in a ``GetTrip`` - response. See `AIP-157 `__ for context. - Additional views are likely to be added. - - Values: - TRIP_VIEW_UNSPECIFIED (0): - The default value. For backwards-compatibility, the API will - default to an SDK view. To ensure stability and support, - customers are advised to select a ``TripView`` other than - ``SDK``. - SDK (1): - Includes fields that may not be interpretable - or supportable using publicly available - libraries. - JOURNEY_SHARING_V1S (2): - Trip fields are populated for the Journey - Sharing use case. This view is intended for - server-to-server communications. - """ - TRIP_VIEW_UNSPECIFIED = 0 - SDK = 1 - JOURNEY_SHARING_V1S = 2 - - -class Trip(proto.Message): - r"""Trip metadata. - - Attributes: - name (str): - Output only. In the format - "providers/{provider}/trips/{trip}". - vehicle_id (str): - ID of the vehicle making this trip. - trip_status (google.maps.fleetengine_v1.types.TripStatus): - Current status of the trip. - trip_type (google.maps.fleetengine_v1.types.TripType): - The type of the trip. - pickup_point (google.maps.fleetengine_v1.types.TerminalLocation): - Location where customer indicates they will - be picked up. - actual_pickup_point (google.maps.fleetengine_v1.types.StopLocation): - Input only. The actual location when and - where customer was picked up. This field is for - provider to provide feedback on actual pickup - information. - actual_pickup_arrival_point (google.maps.fleetengine_v1.types.StopLocation): - Input only. The actual time and location of - the driver arrival at the pickup point. - This field is for provider to provide feedback - on actual arrival information at the pickup - point. - pickup_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Either the estimated future time - when the rider(s) will be picked up, or the - actual time when they were picked up. - intermediate_destinations (MutableSequence[google.maps.fleetengine_v1.types.TerminalLocation]): - Intermediate stops in order that the trip - requests (in addition to pickup and dropoff). - Initially this will not be supported for shared - trips. - intermediate_destinations_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the last time the ``intermediate_destinations`` - was modified. Your server should cache this value and pass - it in ``UpdateTripRequest`` when update - ``intermediate_destination_index`` to ensure the - ``intermediate_destinations`` is not changed. - intermediate_destination_index (int): - When ``TripStatus`` is - ``ENROUTE_TO_INTERMEDIATE_DESTINATION``, a number between - [0..N-1] indicating which intermediate destination the - vehicle will cross next. When ``TripStatus`` is - ``ARRIVED_AT_INTERMEDIATE_DESTINATION``, a number between - [0..N-1] indicating which intermediate destination the - vehicle is at. The provider sets this value. If there are no - ``intermediate_destinations``, this field is ignored. - actual_intermediate_destination_arrival_points (MutableSequence[google.maps.fleetengine_v1.types.StopLocation]): - Input only. The actual time and location of - the driver's arrival at an intermediate - destination. This field is for provider to - provide feedback on actual arrival information - at intermediate destinations. - actual_intermediate_destinations (MutableSequence[google.maps.fleetengine_v1.types.StopLocation]): - Input only. The actual time and location when - and where the customer was picked up from an - intermediate destination. This field is for - provider to provide feedback on actual pickup - information at intermediate destinations. - dropoff_point (google.maps.fleetengine_v1.types.TerminalLocation): - Location where customer indicates they will - be dropped off. - actual_dropoff_point (google.maps.fleetengine_v1.types.StopLocation): - Input only. The actual time and location when - and where customer was dropped off. This field - is for provider to provide feedback on actual - dropoff information. - dropoff_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Either the estimated future time - when the rider(s) will be dropped off at the - final destination, or the actual time when they - were dropped off. - remaining_waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): - Output only. The full path from the current - location to the dropoff point, inclusive. This - path could include waypoints from other trips. - vehicle_waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): - This field supports manual ordering of the waypoints for the - trip. It contains all of the remaining waypoints for the - assigned vehicle, as well as the pickup and drop-off - waypoints for this trip. If the trip hasn't been assigned to - a vehicle, then Fleet Engine ignores this field. For privacy - reasons, this field is only populated by the server on - ``UpdateTrip`` and ``CreateTrip`` calls, NOT on ``GetTrip`` - calls. - route (MutableSequence[google.type.latlng_pb2.LatLng]): - Output only. Anticipated route for this trip to the first - entry in remaining_waypoints. Note that the first waypoint - may belong to a different trip. - current_route_segment (str): - Output only. An encoded path to the next - waypoint. - Note: This field is intended only for use by the - Driver SDK and Consumer SDK. Decoding is not yet - supported. - current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Indicates the last time the - route was modified. - Note: This field is intended only for use by the - Driver SDK and Consumer SDK. - current_route_segment_traffic (google.maps.fleetengine_v1.types.ConsumableTrafficPolyline): - Output only. Indicates the traffic conditions along the - ``current_route_segment`` when they're available. - - Note: This field is intended only for use by the Driver SDK - and Consumer SDK. - current_route_segment_traffic_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Indicates the last time the - ``current_route_segment_traffic`` was modified. - - Note: This field is intended only for use by the Driver SDK - and Consumer SDK. - current_route_segment_end_point (google.maps.fleetengine_v1.types.TripWaypoint): - Output only. The waypoint where ``current_route_segment`` - ends. - remaining_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - Output only. The remaining driving distance in the - ``current_route_segment`` field. The value is unspecified if - the trip is not assigned to a vehicle, or the trip is - completed or cancelled. - eta_to_first_waypoint (google.protobuf.timestamp_pb2.Timestamp): - Output only. The ETA to the next waypoint (the first entry - in the ``remaining_waypoints`` field). The value is - unspecified if the trip is not assigned to a vehicle, or the - trip is inactive (completed or cancelled). - remaining_time_to_first_waypoint (google.protobuf.duration_pb2.Duration): - Output only. The duration from when the Trip data is - returned to the time in ``Trip.eta_to_first_waypoint``. The - value is unspecified if the trip is not assigned to a - vehicle, or the trip is inactive (completed or cancelled). - remaining_waypoints_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Indicates the last time that - ``remaining_waypoints`` was changed (a waypoint was added, - removed, or changed). - remaining_waypoints_route_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Indicates the last time the - ``remaining_waypoints.path_to_waypoint`` and - ``remaining_waypoints.traffic_to_waypoint`` were modified. - Your client app should cache this value and pass it in - ``GetTripRequest`` to ensure the paths and traffic for - ``remaining_waypoints`` are only returned if updated. - number_of_passengers (int): - Immutable. Indicates the number of passengers on this trip - and does not include the driver. A vehicle must have - available capacity to be returned in a ``SearchVehicles`` - response. - last_location (google.maps.fleetengine_v1.types.VehicleLocation): - Output only. Indicates the last reported - location of the vehicle along the route. - last_location_snappable (bool): - Output only. Indicates whether the vehicle's - ``last_location`` can be snapped to the - current_route_segment. False if ``last_location`` or - ``current_route_segment`` doesn't exist. It is computed by - Fleet Engine. Any update from clients will be ignored. - view (google.maps.fleetengine_v1.types.TripView): - The subset of Trip fields that are populated - and how they should be interpreted. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - vehicle_id: str = proto.Field( - proto.STRING, - number=2, - ) - trip_status: 'TripStatus' = proto.Field( - proto.ENUM, - number=3, - enum='TripStatus', - ) - trip_type: fleetengine.TripType = proto.Field( - proto.ENUM, - number=4, - enum=fleetengine.TripType, - ) - pickup_point: fleetengine.TerminalLocation = proto.Field( - proto.MESSAGE, - number=5, - message=fleetengine.TerminalLocation, - ) - actual_pickup_point: 'StopLocation' = proto.Field( - proto.MESSAGE, - number=22, - message='StopLocation', - ) - actual_pickup_arrival_point: 'StopLocation' = proto.Field( - proto.MESSAGE, - number=32, - message='StopLocation', - ) - pickup_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - intermediate_destinations: MutableSequence[fleetengine.TerminalLocation] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=fleetengine.TerminalLocation, - ) - intermediate_destinations_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=25, - message=timestamp_pb2.Timestamp, - ) - intermediate_destination_index: int = proto.Field( - proto.INT32, - number=15, - ) - actual_intermediate_destination_arrival_points: MutableSequence['StopLocation'] = proto.RepeatedField( - proto.MESSAGE, - number=33, - message='StopLocation', - ) - actual_intermediate_destinations: MutableSequence['StopLocation'] = proto.RepeatedField( - proto.MESSAGE, - number=34, - message='StopLocation', - ) - dropoff_point: fleetengine.TerminalLocation = proto.Field( - proto.MESSAGE, - number=7, - message=fleetengine.TerminalLocation, - ) - actual_dropoff_point: 'StopLocation' = proto.Field( - proto.MESSAGE, - number=23, - message='StopLocation', - ) - dropoff_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - remaining_waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( - proto.MESSAGE, - number=16, - message=fleetengine.TripWaypoint, - ) - vehicle_waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( - proto.MESSAGE, - number=20, - message=fleetengine.TripWaypoint, - ) - route: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=latlng_pb2.LatLng, - ) - current_route_segment: str = proto.Field( - proto.STRING, - number=21, - ) - current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=17, - message=timestamp_pb2.Timestamp, - ) - current_route_segment_traffic: traffic.ConsumableTrafficPolyline = proto.Field( - proto.MESSAGE, - number=28, - message=traffic.ConsumableTrafficPolyline, - ) - current_route_segment_traffic_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=30, - message=timestamp_pb2.Timestamp, - ) - current_route_segment_end_point: fleetengine.TripWaypoint = proto.Field( - proto.MESSAGE, - number=24, - message=fleetengine.TripWaypoint, - ) - remaining_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=12, - message=wrappers_pb2.Int32Value, - ) - eta_to_first_waypoint: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=13, - message=timestamp_pb2.Timestamp, - ) - remaining_time_to_first_waypoint: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=27, - message=duration_pb2.Duration, - ) - remaining_waypoints_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - message=timestamp_pb2.Timestamp, - ) - remaining_waypoints_route_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=29, - message=timestamp_pb2.Timestamp, - ) - number_of_passengers: int = proto.Field( - proto.INT32, - number=10, - ) - last_location: fleetengine.VehicleLocation = proto.Field( - proto.MESSAGE, - number=11, - message=fleetengine.VehicleLocation, - ) - last_location_snappable: bool = proto.Field( - proto.BOOL, - number=26, - ) - view: 'TripView' = proto.Field( - proto.ENUM, - number=31, - enum='TripView', - ) - - -class StopLocation(proto.Message): - r"""The actual location where a stop (pickup/dropoff) happened. - - Attributes: - point (google.type.latlng_pb2.LatLng): - Required. Denotes the actual location. - timestamp (google.protobuf.timestamp_pb2.Timestamp): - Indicates when the stop happened. - stop_time (google.protobuf.timestamp_pb2.Timestamp): - Input only. Deprecated. Use the timestamp - field. - """ - - point: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - timestamp: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - stop_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py deleted file mode 100644 index 359753c644e4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicle_api.py +++ /dev/null @@ -1,1047 +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.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import header as mf_header -from google.maps.fleetengine_v1.types import vehicles as mf_vehicles -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'CreateVehicleRequest', - 'GetVehicleRequest', - 'UpdateVehicleRequest', - 'UpdateVehicleAttributesRequest', - 'UpdateVehicleAttributesResponse', - 'SearchVehiclesRequest', - 'SearchVehiclesResponse', - 'ListVehiclesRequest', - 'ListVehiclesResponse', - 'Waypoint', - 'VehicleMatch', - 'VehicleAttributeList', - }, -) - - -class CreateVehicleRequest(proto.Message): - r"""``CreateVehicle`` request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - vehicle_id (str): - Required. Unique Vehicle ID. Subject to the following - restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form C] - (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII characters: - '/', ':', '?', ',', or '#'. - vehicle (google.maps.fleetengine_v1.types.Vehicle): - Required. The Vehicle entity to create. When creating a - Vehicle, the following fields are required: - - - ``vehicleState`` - - ``supportedTripTypes`` - - ``maximumCapacity`` - - ``vehicleType`` - - When creating a Vehicle, the following fields are ignored: - - - ``name`` - - ``currentTrips`` - - ``availableCapacity`` - - ``current_route_segment`` - - ``current_route_segment_end_point`` - - ``current_route_segment_version`` - - ``current_route_segment_traffic`` - - ``route`` - - ``waypoints`` - - ``waypoints_version`` - - ``remaining_distance_meters`` - - ``remaining_time_seconds`` - - ``eta_to_next_waypoint`` - - ``navigation_status`` - - All other fields are optional and used if provided. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - vehicle_id: str = proto.Field( - proto.STRING, - number=4, - ) - vehicle: mf_vehicles.Vehicle = proto.Field( - proto.MESSAGE, - number=5, - message=mf_vehicles.Vehicle, - ) - - -class GetVehicleRequest(proto.Message): - r"""``GetVehicle`` request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - name (str): - Required. Must be in the format - ``providers/{provider}/vehicles/{vehicle}``. The provider - must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Vehicle.current_route_segment`` is retrieved. If the route - is unchanged since this timestamp, the - ``current_route_segment`` field is not set in the response. - If a minimum is unspecified, the ``current_route_segment`` - is always retrieved. - waypoints_version (google.protobuf.timestamp_pb2.Timestamp): - Indicates the minimum timestamp (exclusive) for which - ``Vehicle.waypoints`` data is retrieved. If the waypoints - are unchanged since this timestamp, the - ``vehicle.waypoints`` data is not set in the response. If - this field is unspecified, ``vehicle.waypoints`` is always - retrieved. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - waypoints_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - - -class UpdateVehicleRequest(proto.Message): - r"""\`UpdateVehicle request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - name (str): - Required. Must be in the format - ``providers/{provider}/vehicles/{vehicle}``. The {provider} - must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - vehicle (google.maps.fleetengine_v1.types.Vehicle): - Required. The ``Vehicle`` entity values to apply. When - updating a ``Vehicle``, the following fields may not be - updated as they are managed by the server. - - - ``available_capacity`` - - ``current_route_segment_version`` - - ``current_trips`` - - ``name`` - - ``waypoints_version`` - - If the ``attributes`` field is updated, **all** the - vehicle's attributes are replaced with the attributes - provided in the request. If you want to update only some - attributes, see the ``UpdateVehicleAttributes`` method. - - Likewise, the ``waypoints`` field can be updated, but must - contain all the waypoints currently on the vehicle, and no - other waypoints. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. A field mask indicating which fields of the - ``Vehicle`` to update. At least one field name must be - provided. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - vehicle: mf_vehicles.Vehicle = proto.Field( - proto.MESSAGE, - number=4, - message=mf_vehicles.Vehicle, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateVehicleAttributesRequest(proto.Message): - r"""``UpdateVehicleAttributes`` request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - name (str): - Required. Must be in the format - ``providers/{provider}/vehicles/{vehicle}``. The provider - must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): - Required. The vehicle attributes to update. - Unmentioned attributes are not altered or - removed. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=fleetengine.VehicleAttribute, - ) - - -class UpdateVehicleAttributesResponse(proto.Message): - r"""``UpdateVehicleAttributes`` response message. - - Attributes: - attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): - Required. The updated full list of vehicle - attributes, including new, altered, and - untouched attributes. - """ - - attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=fleetengine.VehicleAttribute, - ) - - -class SearchVehiclesRequest(proto.Message): - r"""``SearchVehicles`` request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - pickup_point (google.maps.fleetengine_v1.types.TerminalLocation): - Required. The pickup point to search near. - dropoff_point (google.maps.fleetengine_v1.types.TerminalLocation): - The customer's intended dropoff location. The field is - required if ``trip_types`` contains ``TripType.SHARED``. - pickup_radius_meters (int): - Required. Defines the vehicle search radius - around the pickup point. Only vehicles within - the search radius will be returned. Value must - be between 400 and 10000 meters (inclusive). - count (int): - Required. Specifies the maximum number of - vehicles to return. The value must be between 1 - and 50 (inclusive). - minimum_capacity (int): - Required. Specifies the number of passengers - being considered for a trip. The value must be - greater than or equal to one. The driver is not - considered in the capacity value. - trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): - Required. Represents the type of proposed trip. Must include - exactly one type. ``UNKNOWN_TRIP_TYPE`` is not allowed. - Restricts the search to only those vehicles that can support - that trip type. - maximum_staleness (google.protobuf.duration_pb2.Duration): - Restricts the search to only those vehicles - that have sent location updates to Fleet Engine - within the specified duration. Stationary - vehicles still transmitting their locations are - not considered stale. If this field is not set, - the server uses five minutes as the default - value. - vehicle_types (MutableSequence[google.maps.fleetengine_v1.types.Vehicle.VehicleType]): - Required. Restricts the search to vehicles with one of the - specified types. At least one vehicle type must be - specified. VehicleTypes with a category of ``UNKNOWN`` are - not allowed. - required_attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): - Callers can form complex logical operations using any - combination of the ``required_attributes``, - ``required_one_of_attributes``, and - ``required_one_of_attribute_sets`` fields. - - ``required_attributes`` is a list; - ``required_one_of_attributes`` uses a message which allows a - list of lists. In combination, the two fields allow the - composition of this expression: - - :: - - (required_attributes[0] AND required_attributes[1] AND ...) - AND - (required_one_of_attributes[0][0] OR required_one_of_attributes[0][1] OR - ...) - AND - (required_one_of_attributes[1][0] OR required_one_of_attributes[1][1] OR - ...) - - Restricts the search to only those vehicles with the - specified attributes. This field is a conjunction/AND - operation. A max of 50 required_attributes is allowed. This - matches the maximum number of attributes allowed on a - vehicle. - required_one_of_attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttributeList]): - Restricts the search to only those vehicles with at least - one of the specified attributes in each - ``VehicleAttributeList``. Within each list, a vehicle must - match at least one of the attributes. This field is an - inclusive disjunction/OR operation in each - ``VehicleAttributeList`` and a conjunction/AND operation - across the collection of ``VehicleAttributeList``. - required_one_of_attribute_sets (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttributeList]): - ``required_one_of_attribute_sets`` provides additional - functionality. - - Similar to ``required_one_of_attributes``, - ``required_one_of_attribute_sets`` uses a message which - allows a list of lists, allowing expressions such as this - one: - - :: - - (required_attributes[0] AND required_attributes[1] AND ...) - AND - ( - (required_one_of_attribute_sets[0][0] AND - required_one_of_attribute_sets[0][1] AND - ...) - OR - (required_one_of_attribute_sets[1][0] AND - required_one_of_attribute_sets[1][1] AND - ...) - ) - - Restricts the search to only those vehicles with all the - attributes in a ``VehicleAttributeList``. Within each list, - a vehicle must match all of the attributes. This field is a - conjunction/AND operation in each ``VehicleAttributeList`` - and inclusive disjunction/OR operation across the collection - of ``VehicleAttributeList``. - order_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): - Required. Specifies the desired ordering - criterion for results. - include_back_to_back (bool): - This indicates if vehicles with a single active trip are - eligible for this search. This field is only used when - ``current_trips_present`` is unspecified. When - ``current_trips_present`` is unspecified and this field is - ``false``, vehicles with assigned trips are excluded from - the search results. When ``current_trips_present`` is - unspecified and this field is ``true``, search results can - include vehicles with one active trip that has a status of - ``ENROUTE_TO_DROPOFF``. When ``current_trips_present`` is - specified, this field cannot be set to true. - - The default value is ``false``. - trip_id (str): - Indicates the trip associated with this - ``SearchVehicleRequest``. - current_trips_present (google.maps.fleetengine_v1.types.SearchVehiclesRequest.CurrentTripsPresent): - This indicates if vehicles with active trips are eligible - for this search. This must be set to something other than - ``CURRENT_TRIPS_PRESENT_UNSPECIFIED`` if ``trip_type`` - includes ``SHARED``. - filter (str): - Optional. A filter query to apply when searching vehicles. - See http://aip.dev/160 for examples of the filter syntax. - - This field is designed to replace the - ``required_attributes``, ``required_one_of_attributes``, and - ``required_one_of_attributes_sets`` fields. If a non-empty - value is specified here, the following fields must be empty: - ``required_attributes``, ``required_one_of_attributes``, and - ``required_one_of_attributes_sets``. - - This filter functions as an AND clause with other - constraints, such as ``minimum_capacity`` or - ``vehicle_types``. - - Note that the only queries supported are on vehicle - attributes (for example, ``attributes. = `` or - ``attributes. = AND attributes. = ``). - The maximum number of restrictions allowed in a filter query - is 50. - - Also, all attributes are stored as strings, so the only - supported comparisons against attributes are string - comparisons. In order to compare against number or boolean - values, the values must be explicitly quoted to be treated - as strings (for example, ``attributes. = "10"`` or - ``attributes. = "true"``). - """ - class VehicleMatchOrder(proto.Enum): - r"""Specifies the order of the vehicle matches in the response. - - Values: - UNKNOWN_VEHICLE_MATCH_ORDER (0): - Default, used for unspecified or unrecognized - vehicle matches order. - PICKUP_POINT_ETA (1): - Ascending order by vehicle driving time to - the pickup point. - PICKUP_POINT_DISTANCE (2): - Ascending order by vehicle driving distance - to the pickup point. - DROPOFF_POINT_ETA (3): - Ascending order by vehicle driving time to - the dropoff point. This order can only be used - if the dropoff point is specified in the - request. - PICKUP_POINT_STRAIGHT_DISTANCE (4): - Ascending order by straight-line distance - from the vehicle's last reported location to the - pickup point. - COST (5): - Ascending order by the configured match cost. - Match cost is defined as a weighted calculation - between straight-line distance and ETA. Weights - are set with default values and can be modified - per customer. Please contact Google support if - these weights need to be modified for your - project. - """ - UNKNOWN_VEHICLE_MATCH_ORDER = 0 - PICKUP_POINT_ETA = 1 - PICKUP_POINT_DISTANCE = 2 - DROPOFF_POINT_ETA = 3 - PICKUP_POINT_STRAIGHT_DISTANCE = 4 - COST = 5 - - class CurrentTripsPresent(proto.Enum): - r"""Specifies the types of restrictions on a vehicle's current - trips. - - Values: - CURRENT_TRIPS_PRESENT_UNSPECIFIED (0): - The availability of vehicles with trips present is governed - by the ``include_back_to_back`` field. - NONE (1): - Vehicles without trips can appear in search results. When - this value is used, ``include_back_to_back`` cannot be - ``true``. - ANY (2): - Vehicles with at most 5 current trips and 10 waypoints are - included in the search results. When this value is used, - ``include_back_to_back`` cannot be ``true``. - """ - CURRENT_TRIPS_PRESENT_UNSPECIFIED = 0 - NONE = 1 - ANY = 2 - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - pickup_point: fleetengine.TerminalLocation = proto.Field( - proto.MESSAGE, - number=4, - message=fleetengine.TerminalLocation, - ) - dropoff_point: fleetengine.TerminalLocation = proto.Field( - proto.MESSAGE, - number=5, - message=fleetengine.TerminalLocation, - ) - pickup_radius_meters: int = proto.Field( - proto.INT32, - number=6, - ) - count: int = proto.Field( - proto.INT32, - number=7, - ) - minimum_capacity: int = proto.Field( - proto.INT32, - number=8, - ) - trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( - proto.ENUM, - number=9, - enum=fleetengine.TripType, - ) - maximum_staleness: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=10, - message=duration_pb2.Duration, - ) - vehicle_types: MutableSequence[mf_vehicles.Vehicle.VehicleType] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=mf_vehicles.Vehicle.VehicleType, - ) - required_attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=fleetengine.VehicleAttribute, - ) - required_one_of_attributes: MutableSequence['VehicleAttributeList'] = proto.RepeatedField( - proto.MESSAGE, - number=15, - message='VehicleAttributeList', - ) - required_one_of_attribute_sets: MutableSequence['VehicleAttributeList'] = proto.RepeatedField( - proto.MESSAGE, - number=20, - message='VehicleAttributeList', - ) - order_by: VehicleMatchOrder = proto.Field( - proto.ENUM, - number=13, - enum=VehicleMatchOrder, - ) - include_back_to_back: bool = proto.Field( - proto.BOOL, - number=18, - ) - trip_id: str = proto.Field( - proto.STRING, - number=19, - ) - current_trips_present: CurrentTripsPresent = proto.Field( - proto.ENUM, - number=21, - enum=CurrentTripsPresent, - ) - filter: str = proto.Field( - proto.STRING, - number=22, - ) - - -class SearchVehiclesResponse(proto.Message): - r"""``SearchVehicles`` response message. - - Attributes: - matches (MutableSequence[google.maps.fleetengine_v1.types.VehicleMatch]): - List of vehicles that match the ``SearchVehiclesRequest`` - criteria, ordered according to - ``SearchVehiclesRequest.order_by`` field. - """ - - matches: MutableSequence['VehicleMatch'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='VehicleMatch', - ) - - -class ListVehiclesRequest(proto.Message): - r"""``ListVehicles`` request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - page_size (int): - The maximum number of vehicles to return. - Default value: 100. - page_token (str): - The value of the ``next_page_token`` provided by a previous - call to ``ListVehicles`` so that you can paginate through - groups of vehicles. The value is undefined if the filter - criteria of the request is not the same as the filter - criteria for the previous call to ``ListVehicles``. - minimum_capacity (google.protobuf.wrappers_pb2.Int32Value): - Specifies the required minimum capacity of the vehicle. All - vehicles returned will have a ``maximum_capacity`` greater - than or equal to this value. If set, must be greater or - equal to 0. - trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): - Restricts the response to vehicles that - support at least one of the specified trip - types. - maximum_staleness (google.protobuf.duration_pb2.Duration): - Restricts the response to vehicles that have - sent location updates to Fleet Engine within the - specified duration. Stationary vehicles still - transmitting their locations are not considered - stale. If present, must be a valid positive - duration. - vehicle_type_categories (MutableSequence[google.maps.fleetengine_v1.types.Vehicle.VehicleType.Category]): - Required. Restricts the response to vehicles with one of the - specified type categories. ``UNKNOWN`` is not allowed. - required_attributes (MutableSequence[str]): - Callers can form complex logical operations using any - combination of the ``required_attributes``, - ``required_one_of_attributes``, and - ``required_one_of_attribute_sets`` fields. - - ``required_attributes`` is a list; - ``required_one_of_attributes`` uses a message which allows a - list of lists. In combination, the two fields allow the - composition of this expression: - - :: - - (required_attributes[0] AND required_attributes[1] AND ...) - AND - (required_one_of_attributes[0][0] OR required_one_of_attributes[0][1] OR - ...) - AND - (required_one_of_attributes[1][0] OR required_one_of_attributes[1][1] OR - ...) - - Restricts the response to vehicles with the specified - attributes. This field is a conjunction/AND operation. A max - of 50 required_attributes is allowed. This matches the - maximum number of attributes allowed on a vehicle. Each - repeated string should be of the format "key:value". - required_one_of_attributes (MutableSequence[str]): - Restricts the response to vehicles with at least one of the - specified attributes in each ``VehicleAttributeList``. - Within each list, a vehicle must match at least one of the - attributes. This field is an inclusive disjunction/OR - operation in each ``VehicleAttributeList`` and a - conjunction/AND operation across the collection of - ``VehicleAttributeList``. Each repeated string should be of - the format "key1:value1|key2:value2|key3:value3". - required_one_of_attribute_sets (MutableSequence[str]): - ``required_one_of_attribute_sets`` provides additional - functionality. - - Similar to ``required_one_of_attributes``, - ``required_one_of_attribute_sets`` uses a message which - allows a list of lists, allowing expressions such as this - one: - - :: - - (required_attributes[0] AND required_attributes[1] AND ...) - AND - ( - (required_one_of_attribute_sets[0][0] AND - required_one_of_attribute_sets[0][1] AND - ...) - OR - (required_one_of_attribute_sets[1][0] AND - required_one_of_attribute_sets[1][1] AND - ...) - ) - - Restricts the response to vehicles that match all the - attributes in a ``VehicleAttributeList``. Within each list, - a vehicle must match all of the attributes. This field is a - conjunction/AND operation in each ``VehicleAttributeList`` - and inclusive disjunction/OR operation across the collection - of ``VehicleAttributeList``. Each repeated string should be - of the format "key1:value1|key2:value2|key3:value3". - vehicle_state (google.maps.fleetengine_v1.types.VehicleState): - Restricts the response to vehicles that have - this vehicle state. - on_trip_only (bool): - Only return the vehicles with current - trip(s). - filter (str): - Optional. A filter query to apply when listing vehicles. See - http://aip.dev/160 for examples of the filter syntax. - - This field is designed to replace the - ``required_attributes``, ``required_one_of_attributes``, and - ``required_one_of_attributes_sets`` fields. If a non-empty - value is specified here, the following fields must be empty: - ``required_attributes``, ``required_one_of_attributes``, and - ``required_one_of_attributes_sets``. - - This filter functions as an AND clause with other - constraints, such as ``vehicle_state`` or ``on_trip_only``. - - Note that the only queries supported are on vehicle - attributes (for example, ``attributes. = `` or - ``attributes. = AND attributes. = ``). - The maximum number of restrictions allowed in a filter query - is 50. - - Also, all attributes are stored as strings, so the only - supported comparisons against attributes are string - comparisons. In order to compare against number or boolean - values, the values must be explicitly quoted to be treated - as strings (for example, ``attributes. = "10"`` or - ``attributes. = "true"``). - viewport (google.geo.type.types.Viewport): - Optional. A filter that limits the vehicles - returned to those whose last known location was - in the rectangular area defined by the viewport. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=12, - message=mf_header.RequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - minimum_capacity: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.Int32Value, - ) - trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( - proto.ENUM, - number=7, - enum=fleetengine.TripType, - ) - maximum_staleness: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - message=duration_pb2.Duration, - ) - vehicle_type_categories: MutableSequence[mf_vehicles.Vehicle.VehicleType.Category] = proto.RepeatedField( - proto.ENUM, - number=9, - enum=mf_vehicles.Vehicle.VehicleType.Category, - ) - required_attributes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - required_one_of_attributes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=13, - ) - required_one_of_attribute_sets: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=15, - ) - vehicle_state: mf_vehicles.VehicleState = proto.Field( - proto.ENUM, - number=11, - enum=mf_vehicles.VehicleState, - ) - on_trip_only: bool = proto.Field( - proto.BOOL, - number=14, - ) - filter: str = proto.Field( - proto.STRING, - number=16, - ) - viewport: ggt_viewport.Viewport = proto.Field( - proto.MESSAGE, - number=17, - message=ggt_viewport.Viewport, - ) - - -class ListVehiclesResponse(proto.Message): - r"""``ListVehicles`` response message. - - Attributes: - vehicles (MutableSequence[google.maps.fleetengine_v1.types.Vehicle]): - Vehicles matching the criteria in the request. The maximum - number of vehicles returned is determined by the - ``page_size`` field in the request. - next_page_token (str): - Token to retrieve the next page of vehicles, - or empty if there are no more vehicles that meet - the request criteria. - total_size (int): - Required. Total number of vehicles matching - the request criteria across all pages. - """ - - @property - def raw_page(self): - return self - - vehicles: MutableSequence[mf_vehicles.Vehicle] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=mf_vehicles.Vehicle, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT64, - number=3, - ) - - -class Waypoint(proto.Message): - r"""Describes intermediate points along a route for a ``VehicleMatch`` - in a ``SearchVehiclesResponse``. This concept is represented as a - ``TripWaypoint`` in all other endpoints. - - Attributes: - lat_lng (google.type.latlng_pb2.LatLng): - The location of this waypoint. - eta (google.protobuf.timestamp_pb2.Timestamp): - The estimated time that the vehicle will - arrive at this waypoint. - """ - - lat_lng: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - eta: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class VehicleMatch(proto.Message): - r"""Contains the vehicle and related estimates for a vehicle that match - the points of active trips for the vehicle - ``SearchVehiclesRequest``. - - Attributes: - vehicle (google.maps.fleetengine_v1.types.Vehicle): - Required. A vehicle that matches the request. - vehicle_pickup_eta (google.protobuf.timestamp_pb2.Timestamp): - The vehicle's driving ETA to the pickup point specified in - the request. An empty value indicates a failure in - calculating ETA for the vehicle. If - ``SearchVehiclesRequest.include_back_to_back`` was ``true`` - and this vehicle has an active trip, ``vehicle_pickup_eta`` - includes the time required to complete the current active - trip. - vehicle_pickup_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The distance from the Vehicle's current - location to the pickup point specified in the - request, including any intermediate pickup or - dropoff points for existing trips. This distance - comprises the calculated driving (route) - distance, plus the straight line distance - between the navigation end point and the - requested pickup point. (The distance between - the navigation end point and the requested - pickup point is typically small.) An empty value - indicates an error in calculating the distance. - vehicle_pickup_straight_line_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - Required. The straight-line distance between - the vehicle and the pickup point specified in - the request. - vehicle_dropoff_eta (google.protobuf.timestamp_pb2.Timestamp): - The complete vehicle's driving ETA to the drop off point - specified in the request. The ETA includes stopping at any - waypoints before the ``dropoff_point`` specified in the - request. The value will only be populated when a drop off - point is specified in the request. An empty value indicates - an error calculating the ETA. - vehicle_pickup_to_dropoff_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The vehicle's driving distance (in meters) from the pickup - point to the drop off point specified in the request. The - distance is only between the two points and does not include - the vehicle location or any other points that must be - visited before the vehicle visits either the pickup point or - dropoff point. The value will only be populated when a - ``dropoff_point`` is specified in the request. An empty - value indicates a failure in calculating the distance from - the pickup to drop off point specified in the request. - trip_type (google.maps.fleetengine_v1.types.TripType): - Required. The trip type of the request that - was used to calculate the ETA to the pickup - point. - vehicle_trips_waypoints (MutableSequence[google.maps.fleetengine_v1.types.Waypoint]): - The ordered list of waypoints used to - calculate the ETA. The list includes vehicle - location, the pickup points of active trips for - the vehicle, and the pickup points provided in - the request. An empty list indicates a failure - in calculating ETA for the vehicle. - vehicle_match_type (google.maps.fleetengine_v1.types.VehicleMatch.VehicleMatchType): - Type of the vehicle match. - requested_ordered_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): - The order requested for sorting vehicle matches. Equivalent - to ``ordered_by``. - ordered_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): - The order requested for sorting vehicle matches. Equivalent - to ``requested_ordered_by``. - """ - class VehicleMatchType(proto.Enum): - r"""Type of vehicle match. - - Values: - UNKNOWN (0): - Unknown vehicle match type - EXCLUSIVE (1): - The vehicle currently has no trip assigned to - it and can proceed to the pickup point. - BACK_TO_BACK (2): - The vehicle is currently assigned to a trip, - but can proceed to the pickup point after - completing the in-progress trip. ETA and - distance calculations take the existing trip - into account. - CARPOOL (3): - The vehicle has sufficient capacity for a - shared ride. - CARPOOL_BACK_TO_BACK (4): - The vehicle will finish its current, active - trip before proceeding to the pickup point. ETA - and distance calculations take the existing trip - into account. - """ - UNKNOWN = 0 - EXCLUSIVE = 1 - BACK_TO_BACK = 2 - CARPOOL = 3 - CARPOOL_BACK_TO_BACK = 4 - - vehicle: mf_vehicles.Vehicle = proto.Field( - proto.MESSAGE, - number=1, - message=mf_vehicles.Vehicle, - ) - vehicle_pickup_eta: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - vehicle_pickup_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int32Value, - ) - vehicle_pickup_straight_line_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=11, - message=wrappers_pb2.Int32Value, - ) - vehicle_dropoff_eta: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - vehicle_pickup_to_dropoff_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.Int32Value, - ) - trip_type: fleetengine.TripType = proto.Field( - proto.ENUM, - number=6, - enum=fleetengine.TripType, - ) - vehicle_trips_waypoints: MutableSequence['Waypoint'] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message='Waypoint', - ) - vehicle_match_type: VehicleMatchType = proto.Field( - proto.ENUM, - number=8, - enum=VehicleMatchType, - ) - requested_ordered_by: 'SearchVehiclesRequest.VehicleMatchOrder' = proto.Field( - proto.ENUM, - number=9, - enum='SearchVehiclesRequest.VehicleMatchOrder', - ) - ordered_by: 'SearchVehiclesRequest.VehicleMatchOrder' = proto.Field( - proto.ENUM, - number=10, - enum='SearchVehiclesRequest.VehicleMatchOrder', - ) - - -class VehicleAttributeList(proto.Message): - r"""A list-of-lists datatype for vehicle attributes. - - Attributes: - attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): - A list of attributes in this collection. - """ - - attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=fleetengine.VehicleAttribute, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py b/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py deleted file mode 100644 index c4662d189513..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/google/maps/fleetengine_v1/types/vehicles.py +++ /dev/null @@ -1,580 +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.fleetengine_v1.types import fleetengine -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.v1', - manifest={ - 'VehicleState', - 'LocationPowerSaveMode', - 'BatteryStatus', - 'PowerSource', - 'Vehicle', - 'BatteryInfo', - 'DeviceSettings', - 'LicensePlate', - 'VisualTrafficReportPolylineRendering', - 'TrafficPolylineData', - }, -) - - -class VehicleState(proto.Enum): - r"""The state of a ``Vehicle``. - - Values: - UNKNOWN_VEHICLE_STATE (0): - Default, used for unspecified or unrecognized - vehicle states. - OFFLINE (1): - The vehicle is not accepting new trips. Note: - the vehicle may continue to operate in this - state while completing a trip assigned to it. - ONLINE (2): - The vehicle is accepting new trips. - """ - UNKNOWN_VEHICLE_STATE = 0 - OFFLINE = 1 - ONLINE = 2 - - -class LocationPowerSaveMode(proto.Enum): - r"""How location features are configured to behave on the mobile - device when the devices "battery saver" feature is on. - (https://developer.android.com/reference/android/os/PowerManager#getLocationPowerSaveMode()) - - Values: - UNKNOWN_LOCATION_POWER_SAVE_MODE (0): - Undefined LocationPowerSaveMode - LOCATION_MODE_NO_CHANGE (1): - Either the location providers shouldn't be - affected by battery saver, or battery saver is - off. - LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF (2): - The GPS based location provider should be - disabled when battery saver is on and the device - is non-interactive. - LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF (3): - All location providers should be disabled - when battery saver is on and the device is - non-interactive. - LOCATION_MODE_FOREGROUND_ONLY (4): - All the location providers will be kept - available, but location fixes should only be - provided to foreground apps. - LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF (5): - Location will not be turned off, but - LocationManager will throttle all requests to - providers when the device is non-interactive. - """ - UNKNOWN_LOCATION_POWER_SAVE_MODE = 0 - LOCATION_MODE_NO_CHANGE = 1 - LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF = 2 - LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF = 3 - LOCATION_MODE_FOREGROUND_ONLY = 4 - LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF = 5 - - -class BatteryStatus(proto.Enum): - r"""Status of the battery, whether full or charging etc. - - Values: - UNKNOWN_BATTERY_STATUS (0): - Battery status unknown. - BATTERY_STATUS_CHARGING (1): - Battery is being charged. - BATTERY_STATUS_DISCHARGING (2): - Battery is discharging. - BATTERY_STATUS_FULL (3): - Battery is full. - BATTERY_STATUS_NOT_CHARGING (4): - Battery is not charging. - BATTERY_STATUS_POWER_LOW (5): - Battery is low on power. - """ - UNKNOWN_BATTERY_STATUS = 0 - BATTERY_STATUS_CHARGING = 1 - BATTERY_STATUS_DISCHARGING = 2 - BATTERY_STATUS_FULL = 3 - BATTERY_STATUS_NOT_CHARGING = 4 - BATTERY_STATUS_POWER_LOW = 5 - - -class PowerSource(proto.Enum): - r"""Type of the charger being used to charge the battery. - - Values: - UNKNOWN_POWER_SOURCE (0): - Power source unknown. - POWER_SOURCE_AC (1): - Power source is an AC charger. - POWER_SOURCE_USB (2): - Power source is a USB port. - POWER_SOURCE_WIRELESS (3): - Power source is wireless. - POWER_SOURCE_UNPLUGGED (4): - Battery is unplugged. - """ - UNKNOWN_POWER_SOURCE = 0 - POWER_SOURCE_AC = 1 - POWER_SOURCE_USB = 2 - POWER_SOURCE_WIRELESS = 3 - POWER_SOURCE_UNPLUGGED = 4 - - -class Vehicle(proto.Message): - r"""Vehicle metadata. - - Attributes: - name (str): - Output only. The unique name for this vehicle. The format is - ``providers/{provider}/vehicles/{vehicle}``. - vehicle_state (google.maps.fleetengine_v1.types.VehicleState): - The vehicle state. - supported_trip_types (MutableSequence[google.maps.fleetengine_v1.types.TripType]): - Trip types supported by this vehicle. - current_trips (MutableSequence[str]): - Output only. List of ``trip_id``'s for trips currently - assigned to this vehicle. - last_location (google.maps.fleetengine_v1.types.VehicleLocation): - Last reported location of the vehicle. - maximum_capacity (int): - The total numbers of riders this vehicle can - carry. The driver is not considered in this - value. This value must be greater than or equal - to one. - attributes (MutableSequence[google.maps.fleetengine_v1.types.VehicleAttribute]): - List of vehicle attributes. A vehicle can - have at most 100 attributes, and each attribute - must have a unique key. - vehicle_type (google.maps.fleetengine_v1.types.Vehicle.VehicleType): - Required. The type of this vehicle. Can be used to filter - vehicles in ``SearchVehicles`` results. Also influences ETA - and route calculations. - license_plate (google.maps.fleetengine_v1.types.LicensePlate): - License plate information for the vehicle. - route (MutableSequence[google.maps.fleetengine_v1.types.TerminalLocation]): - Deprecated: Use ``Vehicle.waypoints`` instead. - current_route_segment (str): - The polyline specifying the route the driver app intends to - take to the next waypoint. This list is also returned in - ``Trip.current_route_segment`` for all active trips assigned - to the vehicle. - - Note: This field is intended only for use by the Driver SDK. - Decoding is not yet supported. - current_route_segment_traffic (google.maps.fleetengine_v1.types.TrafficPolylineData): - Input only. Fleet Engine uses this - information to improve journey sharing. Note: - This field is intended only for use by the - Driver SDK. - current_route_segment_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when ``current_route_segment`` was set. It - can be stored by the client and passed in future - ``GetVehicle`` requests to prevent returning routes that - haven't changed. - current_route_segment_end_point (google.maps.fleetengine_v1.types.TripWaypoint): - The waypoint where ``current_route_segment`` ends. This can - be supplied by drivers on ``UpdateVehicle`` calls either as - a full trip waypoint, a waypoint ``LatLng``, or as the last - ``LatLng`` of the ``current_route_segment``. Fleet Engine - will then do its best to interpolate to an actual waypoint - if it is not fully specified. This field is ignored in - ``UpdateVehicle`` calls unless ``current_route_segment`` is - also specified. - remaining_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The remaining driving distance for the - ``current_route_segment``. This value is also returned in - ``Trip.remaining_distance_meters`` for all active trips - assigned to the vehicle. The value is unspecified if the - ``current_route_segment`` field is empty. - eta_to_first_waypoint (google.protobuf.timestamp_pb2.Timestamp): - The ETA to the first entry in the ``waypoints`` field. The - value is unspecified if the ``waypoints`` field is empty or - the ``Vehicle.current_route_segment`` field is empty. - - When updating a vehicle, ``remaining_time_seconds`` takes - precedence over ``eta_to_first_waypoint`` in the same - request. - remaining_time_seconds (google.protobuf.wrappers_pb2.Int32Value): - Input only. The remaining driving time for the - ``current_route_segment``. The value is unspecified if the - ``waypoints`` field is empty or the - ``Vehicle.current_route_segment`` field is empty. This value - should match ``eta_to_first_waypoint`` - ``current_time`` if - all parties are using the same clock. - - When updating a vehicle, ``remaining_time_seconds`` takes - precedence over ``eta_to_first_waypoint`` in the same - request. - waypoints (MutableSequence[google.maps.fleetengine_v1.types.TripWaypoint]): - The remaining waypoints assigned to this - Vehicle. - waypoints_version (google.protobuf.timestamp_pb2.Timestamp): - Output only. Last time the ``waypoints`` field was updated. - Clients should cache this value and pass it in - ``GetVehicleRequest`` to ensure the ``waypoints`` field is - only returned if it is updated. - back_to_back_enabled (bool): - Indicates if the driver accepts back-to-back trips. If - ``true``, ``SearchVehicles`` may include the vehicle even if - it is currently assigned to a trip. The default value is - ``false``. - navigation_status (google.maps.fleetengine_v1.types.NavigationStatus): - The vehicle's navigation status. - device_settings (google.maps.fleetengine_v1.types.DeviceSettings): - Input only. Information about settings in the - mobile device being used by the driver. - """ - - class VehicleType(proto.Message): - r"""The type of vehicle. - - Attributes: - category (google.maps.fleetengine_v1.types.Vehicle.VehicleType.Category): - Vehicle type category - """ - class Category(proto.Enum): - r"""Vehicle type categories - - Values: - UNKNOWN (0): - Default, used for unspecified or unrecognized - vehicle categories. - AUTO (1): - An automobile. - TAXI (2): - Any vehicle that acts as a taxi (typically - licensed or regulated). - TRUCK (3): - Generally, a vehicle with a large storage - capacity. - TWO_WHEELER (4): - A motorcycle, moped, or other two-wheeled - vehicle - BICYCLE (5): - Human-powered transport. - PEDESTRIAN (6): - A human transporter, typically walking or - running, traveling along pedestrian pathways. - """ - UNKNOWN = 0 - AUTO = 1 - TAXI = 2 - TRUCK = 3 - TWO_WHEELER = 4 - BICYCLE = 5 - PEDESTRIAN = 6 - - category: 'Vehicle.VehicleType.Category' = proto.Field( - proto.ENUM, - number=1, - enum='Vehicle.VehicleType.Category', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - vehicle_state: 'VehicleState' = proto.Field( - proto.ENUM, - number=2, - enum='VehicleState', - ) - supported_trip_types: MutableSequence[fleetengine.TripType] = proto.RepeatedField( - proto.ENUM, - number=3, - enum=fleetengine.TripType, - ) - current_trips: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - last_location: fleetengine.VehicleLocation = proto.Field( - proto.MESSAGE, - number=5, - message=fleetengine.VehicleLocation, - ) - maximum_capacity: int = proto.Field( - proto.INT32, - number=6, - ) - attributes: MutableSequence[fleetengine.VehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=fleetengine.VehicleAttribute, - ) - vehicle_type: VehicleType = proto.Field( - proto.MESSAGE, - number=9, - message=VehicleType, - ) - license_plate: 'LicensePlate' = proto.Field( - proto.MESSAGE, - number=10, - message='LicensePlate', - ) - route: MutableSequence[fleetengine.TerminalLocation] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message=fleetengine.TerminalLocation, - ) - current_route_segment: str = proto.Field( - proto.STRING, - number=20, - ) - current_route_segment_traffic: 'TrafficPolylineData' = proto.Field( - proto.MESSAGE, - number=28, - message='TrafficPolylineData', - ) - current_route_segment_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=15, - message=timestamp_pb2.Timestamp, - ) - current_route_segment_end_point: fleetengine.TripWaypoint = proto.Field( - proto.MESSAGE, - number=24, - message=fleetengine.TripWaypoint, - ) - remaining_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=18, - message=wrappers_pb2.Int32Value, - ) - eta_to_first_waypoint: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=19, - message=timestamp_pb2.Timestamp, - ) - remaining_time_seconds: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=25, - message=wrappers_pb2.Int32Value, - ) - waypoints: MutableSequence[fleetengine.TripWaypoint] = proto.RepeatedField( - proto.MESSAGE, - number=22, - message=fleetengine.TripWaypoint, - ) - waypoints_version: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=16, - message=timestamp_pb2.Timestamp, - ) - back_to_back_enabled: bool = proto.Field( - proto.BOOL, - number=23, - ) - navigation_status: fleetengine.NavigationStatus = proto.Field( - proto.ENUM, - number=26, - enum=fleetengine.NavigationStatus, - ) - device_settings: 'DeviceSettings' = proto.Field( - proto.MESSAGE, - number=27, - message='DeviceSettings', - ) - - -class BatteryInfo(proto.Message): - r"""Information about the device's battery. - - Attributes: - battery_status (google.maps.fleetengine_v1.types.BatteryStatus): - Status of the battery, whether full or - charging etc. - power_source (google.maps.fleetengine_v1.types.PowerSource): - Status of battery power source. - battery_percentage (float): - Current battery percentage [0-100]. - """ - - battery_status: 'BatteryStatus' = proto.Field( - proto.ENUM, - number=1, - enum='BatteryStatus', - ) - power_source: 'PowerSource' = proto.Field( - proto.ENUM, - number=2, - enum='PowerSource', - ) - battery_percentage: float = proto.Field( - proto.FLOAT, - number=3, - ) - - -class DeviceSettings(proto.Message): - r"""Information about various settings on the mobile device. - - Attributes: - location_power_save_mode (google.maps.fleetengine_v1.types.LocationPowerSaveMode): - How location features are set to behave on - the device when battery saver is on. - is_power_save_mode (bool): - Whether the device is currently in power save - mode. - is_interactive (bool): - Whether the device is in an interactive - state. - battery_info (google.maps.fleetengine_v1.types.BatteryInfo): - Information about the battery state. - """ - - location_power_save_mode: 'LocationPowerSaveMode' = proto.Field( - proto.ENUM, - number=1, - enum='LocationPowerSaveMode', - ) - is_power_save_mode: bool = proto.Field( - proto.BOOL, - number=2, - ) - is_interactive: bool = proto.Field( - proto.BOOL, - number=3, - ) - battery_info: 'BatteryInfo' = proto.Field( - proto.MESSAGE, - number=4, - message='BatteryInfo', - ) - - -class LicensePlate(proto.Message): - r"""The license plate information of the Vehicle. To avoid - storing personally-identifiable information, only the minimum - information about the license plate is stored as part of the - entity. - - Attributes: - country_code (str): - Required. CLDR Country/Region Code. For example, ``US`` for - United States, or ``IN`` for India. - last_character (str): - The last digit of the license plate or "-1" to denote no - numeric value is present in the license plate. - - - "ABC 1234" -> "4" - - "AB 123 CD" -> "3" - - "ABCDEF" -> "-1". - """ - - country_code: str = proto.Field( - proto.STRING, - number=1, - ) - last_character: str = proto.Field( - proto.STRING, - number=2, - ) - - -class VisualTrafficReportPolylineRendering(proto.Message): - r"""Describes how clients should color one portion of the - polyline along the route. - - Attributes: - road_stretch (MutableSequence[google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering.RoadStretch]): - Optional. Road stretches that should be - rendered along the polyline. Stretches are - guaranteed to not overlap, and do not - necessarily span the full route. - - In the absence of a road stretch to style, the - client should apply the default for the route. - """ - - class RoadStretch(proto.Message): - r"""One road stretch that should be rendered. - - Attributes: - style (google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering.RoadStretch.Style): - Required. The style to apply. - offset_meters (int): - Required. The style should be applied between - ``[offset_meters, offset_meters + length_meters)``. - length_meters (int): - Required. The length of the path where to - apply the style. - """ - class Style(proto.Enum): - r"""The traffic style, indicating traffic speed. - - Values: - STYLE_UNSPECIFIED (0): - No style selected. - SLOWER_TRAFFIC (1): - Traffic is slowing down. - TRAFFIC_JAM (2): - There is a traffic jam. - """ - STYLE_UNSPECIFIED = 0 - SLOWER_TRAFFIC = 1 - TRAFFIC_JAM = 2 - - style: 'VisualTrafficReportPolylineRendering.RoadStretch.Style' = proto.Field( - proto.ENUM, - number=1, - enum='VisualTrafficReportPolylineRendering.RoadStretch.Style', - ) - offset_meters: int = proto.Field( - proto.INT32, - number=2, - ) - length_meters: int = proto.Field( - proto.INT32, - number=3, - ) - - road_stretch: MutableSequence[RoadStretch] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=RoadStretch, - ) - - -class TrafficPolylineData(proto.Message): - r"""Traffic conditions along the expected vehicle route. - - Attributes: - traffic_rendering (google.maps.fleetengine_v1.types.VisualTrafficReportPolylineRendering): - A polyline rendering of how fast traffic is - for all regions along one stretch of a customer - ride. - """ - - traffic_rendering: 'VisualTrafficReportPolylineRendering' = proto.Field( - proto.MESSAGE, - number=1, - message='VisualTrafficReportPolylineRendering', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine/v1/mypy.ini b/owl-bot-staging/google-maps-fleetengine/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-maps-fleetengine/v1/noxfile.py b/owl-bot-staging/google-maps-fleetengine/v1/noxfile.py deleted file mode 100644 index 4bc01f860119..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine' - -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/fleetengine_v1/', - '--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/fleetengine_v1/', - '--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-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py deleted file mode 100644 index ab45c932839a..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_async.py +++ /dev/null @@ -1,53 +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 CreateTrip -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_CreateTrip_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 fleetengine_v1 - - -async def sample_create_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateTripRequest( - parent="parent_value", - trip_id="trip_id_value", - ) - - # Make the request - response = await client.create_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_CreateTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py deleted file mode 100644 index c4644b1862d3..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_create_trip_sync.py +++ /dev/null @@ -1,53 +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 CreateTrip -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_CreateTrip_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 fleetengine_v1 - - -def sample_create_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateTripRequest( - parent="parent_value", - trip_id="trip_id_value", - ) - - # Make the request - response = client.create_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_CreateTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_async.py deleted file mode 100644 index 0c2d7cd52ca9..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_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 GetTrip -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_GetTrip_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 fleetengine_v1 - - -async def sample_get_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetTripRequest( - name="name_value", - ) - - # Make the request - response = await client.get_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_GetTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_sync.py deleted file mode 100644 index d3bfcfe709c0..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_get_trip_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 GetTrip -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_GetTrip_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 fleetengine_v1 - - -def sample_get_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetTripRequest( - name="name_value", - ) - - # Make the request - response = client.get_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_GetTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_async.py deleted file mode 100644 index 8e32e9b6f3a9..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_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 ReportBillableTrip -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_ReportBillableTrip_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 fleetengine_v1 - - -async def sample_report_billable_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.ReportBillableTripRequest( - name="name_value", - country_code="country_code_value", - ) - - # Make the request - await client.report_billable_trip(request=request) - - -# [END fleetengine_v1_generated_TripService_ReportBillableTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_sync.py deleted file mode 100644 index 0ea03be8d902..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_report_billable_trip_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 ReportBillableTrip -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_ReportBillableTrip_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 fleetengine_v1 - - -def sample_report_billable_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.ReportBillableTripRequest( - name="name_value", - country_code="country_code_value", - ) - - # Make the request - client.report_billable_trip(request=request) - - -# [END fleetengine_v1_generated_TripService_ReportBillableTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py deleted file mode 100644 index 5cd30f613daa..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_async.py +++ /dev/null @@ -1,53 +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 SearchTrips -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_SearchTrips_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 fleetengine_v1 - - -async def sample_search_trips(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchTripsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_trips(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END fleetengine_v1_generated_TripService_SearchTrips_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py deleted file mode 100644 index dfbbfe500c95..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_search_trips_sync.py +++ /dev/null @@ -1,53 +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 SearchTrips -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_SearchTrips_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 fleetengine_v1 - - -def sample_search_trips(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchTripsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.search_trips(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END fleetengine_v1_generated_TripService_SearchTrips_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_async.py deleted file mode 100644 index f67869a7143d..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_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 UpdateTrip -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_UpdateTrip_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 fleetengine_v1 - - -async def sample_update_trip(): - # Create a client - client = fleetengine_v1.TripServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateTripRequest( - name="name_value", - ) - - # Make the request - response = await client.update_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_UpdateTrip_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_sync.py deleted file mode 100644 index fc41bd61a318..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_trip_service_update_trip_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 UpdateTrip -# 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-fleetengine - - -# [START fleetengine_v1_generated_TripService_UpdateTrip_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 fleetengine_v1 - - -def sample_update_trip(): - # Create a client - client = fleetengine_v1.TripServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateTripRequest( - name="name_value", - ) - - # Make the request - response = client.update_trip(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_TripService_UpdateTrip_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py deleted file mode 100644 index 851946fd95a3..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_async.py +++ /dev/null @@ -1,53 +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 CreateVehicle -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_CreateVehicle_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 fleetengine_v1 - - -async def sample_create_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateVehicleRequest( - parent="parent_value", - vehicle_id="vehicle_id_value", - ) - - # Make the request - response = await client.create_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_CreateVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py deleted file mode 100644 index 24820678e5df..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py +++ /dev/null @@ -1,53 +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 CreateVehicle -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_CreateVehicle_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 fleetengine_v1 - - -def sample_create_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.CreateVehicleRequest( - parent="parent_value", - vehicle_id="vehicle_id_value", - ) - - # Make the request - response = client.create_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_CreateVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_async.py deleted file mode 100644 index 39c32d3272f7..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_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 GetVehicle -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_GetVehicle_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 fleetengine_v1 - - -async def sample_get_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_GetVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py deleted file mode 100644 index 3b852145ad23..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_get_vehicle_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 GetVehicle -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_GetVehicle_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 fleetengine_v1 - - -def sample_get_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.GetVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.get_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_GetVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py deleted file mode 100644 index 969785d1f002..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_async.py +++ /dev/null @@ -1,54 +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 ListVehicles -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_ListVehicles_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 fleetengine_v1 - - -async def sample_list_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.ListVehiclesRequest( - parent="parent_value", - vehicle_type_categories=['PEDESTRIAN'], - ) - - # Make the request - page_result = client.list_vehicles(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END fleetengine_v1_generated_VehicleService_ListVehicles_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py deleted file mode 100644 index 32329e16b91d..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py +++ /dev/null @@ -1,54 +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 ListVehicles -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_ListVehicles_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 fleetengine_v1 - - -def sample_list_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.ListVehiclesRequest( - parent="parent_value", - vehicle_type_categories=['PEDESTRIAN'], - ) - - # Make the request - page_result = client.list_vehicles(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END fleetengine_v1_generated_VehicleService_ListVehicles_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.py deleted file mode 100644 index 72dbea4e2525..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchVehicles -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_SearchVehicles_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 fleetengine_v1 - - -async def sample_search_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = await client.search_vehicles(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_SearchVehicles_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py deleted file mode 100644 index 9d2ea3d1cd7f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_vehicles_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchVehicles -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_SearchVehicles_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 fleetengine_v1 - - -def sample_search_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = client.search_vehicles(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_SearchVehicles_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_async.py deleted file mode 100644 index 83ef89e4566b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_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 UpdateVehicle -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_UpdateVehicle_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 fleetengine_v1 - - -async def sample_update_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.update_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_UpdateVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py deleted file mode 100644 index 9b5d10d7db81..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateVehicleAttributes -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_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 fleetengine_v1 - - -async def sample_update_vehicle_attributes(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - attributes = fleetengine_v1.VehicleAttribute() - attributes.string_value = "string_value_value" - - request = fleetengine_v1.UpdateVehicleAttributesRequest( - name="name_value", - attributes=attributes, - ) - - # Make the request - response = await client.update_vehicle_attributes(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_async] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py deleted file mode 100644 index ae0d5f325998..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateVehicleAttributes -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_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 fleetengine_v1 - - -def sample_update_vehicle_attributes(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - attributes = fleetengine_v1.VehicleAttribute() - attributes.string_value = "string_value_value" - - request = fleetengine_v1.UpdateVehicleAttributesRequest( - name="name_value", - attributes=attributes, - ) - - # Make the request - response = client.update_vehicle_attributes(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py deleted file mode 100644 index f1ae021b0f99..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_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 UpdateVehicle -# 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-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_UpdateVehicle_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 fleetengine_v1 - - -def sample_update_vehicle(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.update_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_UpdateVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json b/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json deleted file mode 100644 index b0139d358773..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json +++ /dev/null @@ -1,1692 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "maps.fleetengine.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-maps-fleetengine", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", - "shortName": "TripServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.create_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.CreateTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "CreateTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.CreateTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "create_trip" - }, - "description": "Sample for CreateTrip", - "file": "fleetengine_v1_generated_trip_service_create_trip_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_CreateTrip_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_create_trip_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceClient", - "shortName": "TripServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceClient.create_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.CreateTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "CreateTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.CreateTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "create_trip" - }, - "description": "Sample for CreateTrip", - "file": "fleetengine_v1_generated_trip_service_create_trip_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_CreateTrip_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_create_trip_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", - "shortName": "TripServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.get_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.GetTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "GetTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.GetTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "get_trip" - }, - "description": "Sample for GetTrip", - "file": "fleetengine_v1_generated_trip_service_get_trip_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_GetTrip_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_get_trip_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceClient", - "shortName": "TripServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceClient.get_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.GetTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "GetTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.GetTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "get_trip" - }, - "description": "Sample for GetTrip", - "file": "fleetengine_v1_generated_trip_service_get_trip_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_GetTrip_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_get_trip_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", - "shortName": "TripServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.report_billable_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.ReportBillableTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "ReportBillableTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.ReportBillableTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "report_billable_trip" - }, - "description": "Sample for ReportBillableTrip", - "file": "fleetengine_v1_generated_trip_service_report_billable_trip_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_ReportBillableTrip_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_report_billable_trip_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceClient", - "shortName": "TripServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceClient.report_billable_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.ReportBillableTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "ReportBillableTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.ReportBillableTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "report_billable_trip" - }, - "description": "Sample for ReportBillableTrip", - "file": "fleetengine_v1_generated_trip_service_report_billable_trip_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_ReportBillableTrip_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_report_billable_trip_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", - "shortName": "TripServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.search_trips", - "method": { - "fullName": "maps.fleetengine.v1.TripService.SearchTrips", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "SearchTrips" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.SearchTripsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsAsyncPager", - "shortName": "search_trips" - }, - "description": "Sample for SearchTrips", - "file": "fleetengine_v1_generated_trip_service_search_trips_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_SearchTrips_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_search_trips_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceClient", - "shortName": "TripServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceClient.search_trips", - "method": { - "fullName": "maps.fleetengine.v1.TripService.SearchTrips", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "SearchTrips" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.SearchTripsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.services.trip_service.pagers.SearchTripsPager", - "shortName": "search_trips" - }, - "description": "Sample for SearchTrips", - "file": "fleetengine_v1_generated_trip_service_search_trips_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_SearchTrips_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_search_trips_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient", - "shortName": "TripServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceAsyncClient.update_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.UpdateTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "UpdateTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "update_trip" - }, - "description": "Sample for UpdateTrip", - "file": "fleetengine_v1_generated_trip_service_update_trip_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_UpdateTrip_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_update_trip_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.TripServiceClient", - "shortName": "TripServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.TripServiceClient.update_trip", - "method": { - "fullName": "maps.fleetengine.v1.TripService.UpdateTrip", - "service": { - "fullName": "maps.fleetengine.v1.TripService", - "shortName": "TripService" - }, - "shortName": "UpdateTrip" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateTripRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Trip", - "shortName": "update_trip" - }, - "description": "Sample for UpdateTrip", - "file": "fleetengine_v1_generated_trip_service_update_trip_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_TripService_UpdateTrip_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_trip_service_update_trip_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.create_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.CreateVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "CreateVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.CreateVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "create_vehicle" - }, - "description": "Sample for CreateVehicle", - "file": "fleetengine_v1_generated_vehicle_service_create_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_CreateVehicle_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_create_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.create_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.CreateVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "CreateVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.CreateVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "create_vehicle" - }, - "description": "Sample for CreateVehicle", - "file": "fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_CreateVehicle_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_create_vehicle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.get_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.GetVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "GetVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.GetVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "get_vehicle" - }, - "description": "Sample for GetVehicle", - "file": "fleetengine_v1_generated_vehicle_service_get_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_GetVehicle_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_get_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.get_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.GetVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "GetVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.GetVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "get_vehicle" - }, - "description": "Sample for GetVehicle", - "file": "fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_GetVehicle_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_get_vehicle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.list_vehicles", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.ListVehicles", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "ListVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.ListVehiclesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesAsyncPager", - "shortName": "list_vehicles" - }, - "description": "Sample for ListVehicles", - "file": "fleetengine_v1_generated_vehicle_service_list_vehicles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_ListVehicles_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_list_vehicles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.list_vehicles", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.ListVehicles", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "ListVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.ListVehiclesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.services.vehicle_service.pagers.ListVehiclesPager", - "shortName": "list_vehicles" - }, - "description": "Sample for ListVehicles", - "file": "fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_ListVehicles_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.search_vehicles", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.SearchVehicles", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "SearchVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.SearchVehiclesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.SearchVehiclesResponse", - "shortName": "search_vehicles" - }, - "description": "Sample for SearchVehicles", - "file": "fleetengine_v1_generated_vehicle_service_search_vehicles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_SearchVehicles_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_search_vehicles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.search_vehicles", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.SearchVehicles", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "SearchVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.SearchVehiclesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.SearchVehiclesResponse", - "shortName": "search_vehicles" - }, - "description": "Sample for SearchVehicles", - "file": "fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_SearchVehicles_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_search_vehicles_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.update_vehicle_attributes", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicleAttributes", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "UpdateVehicleAttributes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse", - "shortName": "update_vehicle_attributes" - }, - "description": "Sample for UpdateVehicleAttributes", - "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.update_vehicle_attributes", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicleAttributes", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "UpdateVehicleAttributes" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.UpdateVehicleAttributesResponse", - "shortName": "update_vehicle_attributes" - }, - "description": "Sample for UpdateVehicleAttributes", - "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicleAttributes_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.update_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "UpdateVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "update_vehicle" - }, - "description": "Sample for UpdateVehicle", - "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicle_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_update_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.update_vehicle", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicle", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "UpdateVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateVehicleRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.Vehicle", - "shortName": "update_vehicle" - }, - "description": "Sample for UpdateVehicle", - "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicle_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_update_vehicle_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py b/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py deleted file mode 100644 index 1a4c9837d26c..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/scripts/fixup_fleetengine_v1_keywords.py +++ /dev/null @@ -1,186 +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 fleetengineCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_trip': ('parent', 'trip_id', 'trip', 'header', ), - 'create_vehicle': ('parent', 'vehicle_id', 'vehicle', 'header', ), - 'get_trip': ('name', 'header', 'view', 'current_route_segment_version', 'remaining_waypoints_version', 'route_format_type', 'current_route_segment_traffic_version', 'remaining_waypoints_route_version', ), - 'get_vehicle': ('name', 'header', 'current_route_segment_version', 'waypoints_version', ), - 'list_vehicles': ('parent', 'vehicle_type_categories', 'header', 'page_size', 'page_token', 'minimum_capacity', 'trip_types', 'maximum_staleness', 'required_attributes', 'required_one_of_attributes', 'required_one_of_attribute_sets', 'vehicle_state', 'on_trip_only', 'filter', 'viewport', ), - 'report_billable_trip': ('name', 'country_code', 'platform', 'related_ids', 'solution_type', ), - 'search_trips': ('parent', 'header', 'vehicle_id', 'active_trips_only', 'page_size', 'page_token', 'minimum_staleness', ), - 'search_vehicles': ('parent', 'pickup_point', 'pickup_radius_meters', 'count', 'minimum_capacity', 'trip_types', 'vehicle_types', 'order_by', 'header', 'dropoff_point', 'maximum_staleness', 'required_attributes', 'required_one_of_attributes', 'required_one_of_attribute_sets', 'include_back_to_back', 'trip_id', 'current_trips_present', 'filter', ), - 'update_trip': ('name', 'trip', 'update_mask', 'header', ), - 'update_vehicle': ('name', 'vehicle', 'update_mask', 'header', ), - 'update_vehicle_attributes': ('name', 'attributes', 'header', ), - } - - 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=fleetengineCallTransformer(), -): - """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 fleetengine 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-fleetengine/v1/setup.py b/owl-bot-staging/google-maps-fleetengine/v1/setup.py deleted file mode 100644 index b805ff698554..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine' - - -description = "Google Maps Fleetengine API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/fleetengine/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-fleetengine" - -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-fleetengine/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.10.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.11.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.12.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.13.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.7.txt deleted file mode 100644 index 277853c664a0..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.8.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-fleetengine/v1/testing/constraints-3.9.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/tests/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/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-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/__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-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py deleted file mode 100644 index bb902fed5d70..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_trip_service.py +++ /dev/null @@ -1,3025 +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 -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 - -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.fleetengine_v1.services.trip_service import TripServiceAsyncClient -from google.maps.fleetengine_v1.services.trip_service import TripServiceClient -from google.maps.fleetengine_v1.services.trip_service import pagers -from google.maps.fleetengine_v1.services.trip_service import transports -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import header -from google.maps.fleetengine_v1.types import traffic -from google.maps.fleetengine_v1.types import trip_api -from google.maps.fleetengine_v1.types import trips -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_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 TripServiceClient._get_default_mtls_endpoint(None) is None - assert TripServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TripServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TripServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TripServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TripServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert TripServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert TripServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert TripServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - TripServiceClient._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 TripServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert TripServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert TripServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - TripServiceClient._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 TripServiceClient._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 TripServiceClient._get_client_cert_source(None, False) is None - assert TripServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert TripServiceClient._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 TripServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert TripServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) -@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = TripServiceClient._DEFAULT_UNIVERSE - default_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert TripServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert TripServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TripServiceClient.DEFAULT_MTLS_ENDPOINT - assert TripServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert TripServiceClient._get_api_endpoint(None, None, default_universe, "always") == TripServiceClient.DEFAULT_MTLS_ENDPOINT - assert TripServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TripServiceClient.DEFAULT_MTLS_ENDPOINT - assert TripServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert TripServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - TripServiceClient._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 TripServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert TripServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert TripServiceClient._get_universe_domain(None, None) == TripServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - TripServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (TripServiceClient, "grpc"), - (TripServiceAsyncClient, "grpc_asyncio"), -]) -def test_trip_service_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 == ( - 'fleetengine.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.TripServiceGrpcTransport, "grpc"), - (transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_trip_service_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", [ - (TripServiceClient, "grpc"), - (TripServiceAsyncClient, "grpc_asyncio"), -]) -def test_trip_service_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 == ( - 'fleetengine.googleapis.com:443' - ) - - -def test_trip_service_client_get_transport_class(): - transport = TripServiceClient.get_transport_class() - available_transports = [ - transports.TripServiceGrpcTransport, - ] - assert transport in available_transports - - transport = TripServiceClient.get_transport_class("grpc") - assert transport == transports.TripServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc"), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) -@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) -def test_trip_service_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(TripServiceClient, '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(TripServiceClient, '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", [ - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", "true"), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", "false"), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) -@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_trip_service_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", [ - TripServiceClient, TripServiceAsyncClient -]) -@mock.patch.object(TripServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TripServiceClient)) -@mock.patch.object(TripServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TripServiceAsyncClient)) -def test_trip_service_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", [ - TripServiceClient, TripServiceAsyncClient -]) -@mock.patch.object(TripServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceClient)) -@mock.patch.object(TripServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TripServiceAsyncClient)) -def test_trip_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = TripServiceClient._DEFAULT_UNIVERSE - default_endpoint = TripServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = TripServiceClient._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", [ - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc"), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_trip_service_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", [ - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", grpc_helpers), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_trip_service_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_trip_service_client_client_options_from_dict(): - with mock.patch('google.maps.fleetengine_v1.services.trip_service.transports.TripServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = TripServiceClient( - 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", [ - (TripServiceClient, transports.TripServiceGrpcTransport, "grpc", grpc_helpers), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_trip_service_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( - "fleetengine.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="fleetengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - trip_api.CreateTripRequest, - dict, -]) -def test_create_trip(request_type, transport: str = 'grpc'): - client = TripServiceClient( - 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.create_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - ) - response = client.create_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = trip_api.CreateTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -def test_create_trip_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 = TripServiceClient( - 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 = trip_api.CreateTripRequest( - parent='parent_value', - trip_id='trip_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_trip), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_trip(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == trip_api.CreateTripRequest( - parent='parent_value', - trip_id='trip_id_value', - ) - -def test_create_trip_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 = TripServiceClient( - 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.create_trip 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.create_trip] = mock_rpc - request = {} - client.create_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_trip(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_create_trip_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 = TripServiceAsyncClient( - 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.create_trip 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.create_trip] = mock_rpc - - request = {} - await client.create_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_trip(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_create_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.CreateTripRequest): - client = TripServiceAsyncClient( - 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.create_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - response = await client.create_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = trip_api.CreateTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -@pytest.mark.asyncio -async def test_create_trip_async_from_dict(): - await test_create_trip_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - trip_api.GetTripRequest, - dict, -]) -def test_get_trip(request_type, transport: str = 'grpc'): - client = TripServiceClient( - 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.get_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - ) - response = client.get_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = trip_api.GetTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -def test_get_trip_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 = TripServiceClient( - 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 = trip_api.GetTripRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_trip), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_trip(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == trip_api.GetTripRequest( - name='name_value', - ) - -def test_get_trip_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 = TripServiceClient( - 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.get_trip 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.get_trip] = mock_rpc - request = {} - client.get_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_trip(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_get_trip_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 = TripServiceAsyncClient( - 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.get_trip 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.get_trip] = mock_rpc - - request = {} - await client.get_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_trip(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_get_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.GetTripRequest): - client = TripServiceAsyncClient( - 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.get_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - response = await client.get_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = trip_api.GetTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -@pytest.mark.asyncio -async def test_get_trip_async_from_dict(): - await test_get_trip_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - trip_api.ReportBillableTripRequest, - dict, -]) -def test_report_billable_trip(request_type, transport: str = 'grpc'): - client = TripServiceClient( - 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.report_billable_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.report_billable_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = trip_api.ReportBillableTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_report_billable_trip_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 = TripServiceClient( - 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 = trip_api.ReportBillableTripRequest( - name='name_value', - country_code='country_code_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.report_billable_trip(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == trip_api.ReportBillableTripRequest( - name='name_value', - country_code='country_code_value', - ) - -def test_report_billable_trip_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 = TripServiceClient( - 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.report_billable_trip 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.report_billable_trip] = mock_rpc - request = {} - client.report_billable_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.report_billable_trip(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_report_billable_trip_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 = TripServiceAsyncClient( - 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.report_billable_trip 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.report_billable_trip] = mock_rpc - - request = {} - await client.report_billable_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.report_billable_trip(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_report_billable_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.ReportBillableTripRequest): - client = TripServiceAsyncClient( - 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.report_billable_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.report_billable_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = trip_api.ReportBillableTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_report_billable_trip_async_from_dict(): - await test_report_billable_trip_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - trip_api.SearchTripsRequest, - dict, -]) -def test_search_trips(request_type, transport: str = 'grpc'): - client = TripServiceClient( - 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.search_trips), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = trip_api.SearchTripsResponse( - next_page_token='next_page_token_value', - ) - response = client.search_trips(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = trip_api.SearchTripsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchTripsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_trips_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 = TripServiceClient( - 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 = trip_api.SearchTripsRequest( - parent='parent_value', - vehicle_id='vehicle_id_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.search_trips(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == trip_api.SearchTripsRequest( - parent='parent_value', - vehicle_id='vehicle_id_value', - page_token='page_token_value', - ) - -def test_search_trips_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 = TripServiceClient( - 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.search_trips 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.search_trips] = mock_rpc - request = {} - client.search_trips(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_trips(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_search_trips_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 = TripServiceAsyncClient( - 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.search_trips 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.search_trips] = mock_rpc - - request = {} - await client.search_trips(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.search_trips(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_search_trips_async(transport: str = 'grpc_asyncio', request_type=trip_api.SearchTripsRequest): - client = TripServiceAsyncClient( - 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.search_trips), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_trips(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = trip_api.SearchTripsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchTripsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_trips_async_from_dict(): - await test_search_trips_async(request_type=dict) - - -def test_search_trips_pager(transport_name: str = "grpc"): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - trips.Trip(), - ], - next_page_token='abc', - ), - trip_api.SearchTripsResponse( - trips=[], - next_page_token='def', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - ], - next_page_token='ghi', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.search_trips(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, trips.Trip) - for i in results) -def test_search_trips_pages(transport_name: str = "grpc"): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - trips.Trip(), - ], - next_page_token='abc', - ), - trip_api.SearchTripsResponse( - trips=[], - next_page_token='def', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - ], - next_page_token='ghi', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - ], - ), - RuntimeError, - ) - pages = list(client.search_trips(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_trips_async_pager(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - trips.Trip(), - ], - next_page_token='abc', - ), - trip_api.SearchTripsResponse( - trips=[], - next_page_token='def', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - ], - next_page_token='ghi', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_trips(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, trips.Trip) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_trips_async_pages(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - trips.Trip(), - ], - next_page_token='abc', - ), - trip_api.SearchTripsResponse( - trips=[], - next_page_token='def', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - ], - next_page_token='ghi', - ), - trip_api.SearchTripsResponse( - trips=[ - trips.Trip(), - trips.Trip(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.search_trips(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - trip_api.UpdateTripRequest, - dict, -]) -def test_update_trip(request_type, transport: str = 'grpc'): - client = TripServiceClient( - 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.update_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - ) - response = client.update_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = trip_api.UpdateTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -def test_update_trip_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 = TripServiceClient( - 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 = trip_api.UpdateTripRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_trip), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_trip(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == trip_api.UpdateTripRequest( - name='name_value', - ) - -def test_update_trip_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 = TripServiceClient( - 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.update_trip 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.update_trip] = mock_rpc - request = {} - client.update_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_trip(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_update_trip_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 = TripServiceAsyncClient( - 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.update_trip 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.update_trip] = mock_rpc - - request = {} - await client.update_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_trip(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_update_trip_async(transport: str = 'grpc_asyncio', request_type=trip_api.UpdateTripRequest): - client = TripServiceAsyncClient( - 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.update_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - response = await client.update_trip(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = trip_api.UpdateTripRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, trips.Trip) - assert response.name == 'name_value' - assert response.vehicle_id == 'vehicle_id_value' - assert response.trip_status == trips.TripStatus.NEW - assert response.trip_type == fleetengine.TripType.SHARED - assert response.intermediate_destination_index == 3187 - assert response.current_route_segment == 'current_route_segment_value' - assert response.number_of_passengers == 2135 - assert response.last_location_snappable is True - assert response.view == trips.TripView.SDK - - -@pytest.mark.asyncio -async def test_update_trip_async_from_dict(): - await test_update_trip_async(request_type=dict) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TripServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TripServiceClient( - 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 = TripServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TripServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TripServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TripServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.TripServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.TripServiceGrpcTransport, - transports.TripServiceGrpcAsyncIOTransport, -]) -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 = TripServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = TripServiceClient( - 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_create_trip_empty_call_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.create_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.CreateTripRequest() - - 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_get_trip_empty_call_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.get_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.GetTripRequest() - - 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_report_billable_trip_empty_call_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - call.return_value = None - client.report_billable_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.ReportBillableTripRequest() - - 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_search_trips_empty_call_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__') as call: - call.return_value = trip_api.SearchTripsResponse() - client.search_trips(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.SearchTripsRequest() - - 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_update_trip_empty_call_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.update_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.UpdateTripRequest() - - assert args[0] == request_msg - - -def test_create_trip_routing_parameters_request_1_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.create_trip(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.CreateTripRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_get_trip_routing_parameters_request_1_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.get_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.GetTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_report_billable_trip_routing_parameters_request_1_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - call.return_value = None - client.report_billable_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.ReportBillableTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_search_trips_routing_parameters_request_1_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__') as call: - call.return_value = trip_api.SearchTripsResponse() - client.search_trips(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.SearchTripsRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_update_trip_routing_parameters_request_1_grpc(): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_trip), - '__call__') as call: - call.return_value = trips.Trip() - client.update_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.UpdateTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_kind_grpc_asyncio(): - transport = TripServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = TripServiceAsyncClient( - 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_create_trip_empty_call_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.create_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.CreateTripRequest() - - 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_get_trip_empty_call_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.get_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.GetTripRequest() - - 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_report_billable_trip_empty_call_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.report_billable_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.ReportBillableTripRequest() - - 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_search_trips_empty_call_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( - next_page_token='next_page_token_value', - )) - await client.search_trips(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.SearchTripsRequest() - - 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_update_trip_empty_call_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.update_trip(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = trip_api.UpdateTripRequest() - - assert args[0] == request_msg - - -@pytest.mark.asyncio -async def test_create_trip_routing_parameters_request_1_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.create_trip(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.CreateTripRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_get_trip_routing_parameters_request_1_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.get_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.GetTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_report_billable_trip_routing_parameters_request_1_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.report_billable_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.report_billable_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.ReportBillableTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_search_trips_routing_parameters_request_1_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_trips), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trip_api.SearchTripsResponse( - next_page_token='next_page_token_value', - )) - await client.search_trips(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.SearchTripsRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_update_trip_routing_parameters_request_1_grpc_asyncio(): - client = TripServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_trip), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(trips.Trip( - name='name_value', - vehicle_id='vehicle_id_value', - trip_status=trips.TripStatus.NEW, - trip_type=fleetengine.TripType.SHARED, - intermediate_destination_index=3187, - current_route_segment='current_route_segment_value', - number_of_passengers=2135, - last_location_snappable=True, - view=trips.TripView.SDK, - )) - await client.update_trip(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = trip_api.UpdateTripRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.TripServiceGrpcTransport, - ) - -def test_trip_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TripServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_trip_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.fleetengine_v1.services.trip_service.transports.TripServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.TripServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_trip', - 'get_trip', - 'report_billable_trip', - 'search_trips', - 'update_trip', - ) - 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_trip_service_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.fleetengine_v1.services.trip_service.transports.TripServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TripServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_trip_service_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.fleetengine_v1.services.trip_service.transports.TripServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TripServiceTransport() - adc.assert_called_once() - - -def test_trip_service_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) - TripServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TripServiceGrpcTransport, - transports.TripServiceGrpcAsyncIOTransport, - ], -) -def test_trip_service_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=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.TripServiceGrpcTransport, - transports.TripServiceGrpcAsyncIOTransport, - ], -) -def test_trip_service_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.TripServiceGrpcTransport, grpc_helpers), - (transports.TripServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_trip_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "fleetengine.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="fleetengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) -def test_trip_service_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_trip_service_host_no_port(transport_name): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'fleetengine.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_trip_service_host_with_port(transport_name): - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'fleetengine.googleapis.com:8000' - ) - -def test_trip_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TripServiceGrpcTransport( - 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_trip_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TripServiceGrpcAsyncIOTransport( - 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.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) -def test_trip_service_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.TripServiceGrpcTransport, transports.TripServiceGrpcAsyncIOTransport]) -def test_trip_service_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_trip_path(): - provider = "squid" - trip = "clam" - expected = "providers/{provider}/trips/{trip}".format(provider=provider, trip=trip, ) - actual = TripServiceClient.trip_path(provider, trip) - assert expected == actual - - -def test_parse_trip_path(): - expected = { - "provider": "whelk", - "trip": "octopus", - } - path = TripServiceClient.trip_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.parse_trip_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TripServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = TripServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = TripServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = TripServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TripServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = TripServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = TripServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = TripServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = TripServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = TripServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TripServiceClient.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.TripServiceTransport, '_prep_wrapped_messages') as prep: - client = TripServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TripServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = TripServiceClient.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 = TripServiceClient( - 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 = TripServiceAsyncClient( - 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_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = TripServiceClient( - 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", [ - (TripServiceClient, transports.TripServiceGrpcTransport), - (TripServiceAsyncClient, transports.TripServiceGrpcAsyncIOTransport), -]) -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/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py b/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py deleted file mode 100644 index 9853af860e76..000000000000 --- a/owl-bot-staging/google-maps-fleetengine/v1/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py +++ /dev/null @@ -1,3280 +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 -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 - -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.geo.type.types import viewport -from google.maps.fleetengine_v1.services.vehicle_service import VehicleServiceAsyncClient -from google.maps.fleetengine_v1.services.vehicle_service import VehicleServiceClient -from google.maps.fleetengine_v1.services.vehicle_service import pagers -from google.maps.fleetengine_v1.services.vehicle_service import transports -from google.maps.fleetengine_v1.types import fleetengine -from google.maps.fleetengine_v1.types import header -from google.maps.fleetengine_v1.types import traffic -from google.maps.fleetengine_v1.types import vehicle_api -from google.maps.fleetengine_v1.types import vehicles -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_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 VehicleServiceClient._get_default_mtls_endpoint(None) is None - assert VehicleServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert VehicleServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert VehicleServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert VehicleServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert VehicleServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert VehicleServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - VehicleServiceClient._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 VehicleServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert VehicleServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert VehicleServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - VehicleServiceClient._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 VehicleServiceClient._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 VehicleServiceClient._get_client_cert_source(None, False) is None - assert VehicleServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert VehicleServiceClient._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 VehicleServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert VehicleServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) -@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = VehicleServiceClient._DEFAULT_UNIVERSE - default_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert VehicleServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert VehicleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT - assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "always") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT - assert VehicleServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == VehicleServiceClient.DEFAULT_MTLS_ENDPOINT - assert VehicleServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert VehicleServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - VehicleServiceClient._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 VehicleServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert VehicleServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert VehicleServiceClient._get_universe_domain(None, None) == VehicleServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - VehicleServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (VehicleServiceClient, "grpc"), - (VehicleServiceAsyncClient, "grpc_asyncio"), -]) -def test_vehicle_service_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 == ( - 'fleetengine.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.VehicleServiceGrpcTransport, "grpc"), - (transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_vehicle_service_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", [ - (VehicleServiceClient, "grpc"), - (VehicleServiceAsyncClient, "grpc_asyncio"), -]) -def test_vehicle_service_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 == ( - 'fleetengine.googleapis.com:443' - ) - - -def test_vehicle_service_client_get_transport_class(): - transport = VehicleServiceClient.get_transport_class() - available_transports = [ - transports.VehicleServiceGrpcTransport, - ] - assert transport in available_transports - - transport = VehicleServiceClient.get_transport_class("grpc") - assert transport == transports.VehicleServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc"), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) -@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) -def test_vehicle_service_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(VehicleServiceClient, '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(VehicleServiceClient, '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", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", "true"), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", "false"), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) -@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_vehicle_service_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", [ - VehicleServiceClient, VehicleServiceAsyncClient -]) -@mock.patch.object(VehicleServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VehicleServiceClient)) -@mock.patch.object(VehicleServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VehicleServiceAsyncClient)) -def test_vehicle_service_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", [ - VehicleServiceClient, VehicleServiceAsyncClient -]) -@mock.patch.object(VehicleServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceClient)) -@mock.patch.object(VehicleServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(VehicleServiceAsyncClient)) -def test_vehicle_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = VehicleServiceClient._DEFAULT_UNIVERSE - default_endpoint = VehicleServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = VehicleServiceClient._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", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc"), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_vehicle_service_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", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", grpc_helpers), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_vehicle_service_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_vehicle_service_client_client_options_from_dict(): - with mock.patch('google.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = VehicleServiceClient( - 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", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport, "grpc", grpc_helpers), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_vehicle_service_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( - "fleetengine.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="fleetengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - vehicle_api.CreateVehicleRequest, - dict, -]) -def test_create_vehicle(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - 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.create_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - ) - response = client.create_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.CreateVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -def test_create_vehicle_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 = VehicleServiceClient( - 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 = vehicle_api.CreateVehicleRequest( - parent='parent_value', - vehicle_id='vehicle_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.CreateVehicleRequest( - parent='parent_value', - vehicle_id='vehicle_id_value', - ) - -def test_create_vehicle_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 = VehicleServiceClient( - 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.create_vehicle 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.create_vehicle] = mock_rpc - request = {} - client.create_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_vehicle(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_create_vehicle_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 = VehicleServiceAsyncClient( - 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.create_vehicle 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.create_vehicle] = mock_rpc - - request = {} - await client.create_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_vehicle(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_create_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.CreateVehicleRequest): - client = VehicleServiceAsyncClient( - 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.create_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - response = await client.create_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.CreateVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -@pytest.mark.asyncio -async def test_create_vehicle_async_from_dict(): - await test_create_vehicle_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - vehicle_api.GetVehicleRequest, - dict, -]) -def test_get_vehicle(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - 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.get_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - ) - response = client.get_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.GetVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -def test_get_vehicle_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 = VehicleServiceClient( - 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 = vehicle_api.GetVehicleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.GetVehicleRequest( - name='name_value', - ) - -def test_get_vehicle_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 = VehicleServiceClient( - 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.get_vehicle 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.get_vehicle] = mock_rpc - request = {} - client.get_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_vehicle(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_get_vehicle_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 = VehicleServiceAsyncClient( - 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.get_vehicle 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.get_vehicle] = mock_rpc - - request = {} - await client.get_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_vehicle(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_get_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.GetVehicleRequest): - client = VehicleServiceAsyncClient( - 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.get_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - response = await client.get_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.GetVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -@pytest.mark.asyncio -async def test_get_vehicle_async_from_dict(): - await test_get_vehicle_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - vehicle_api.UpdateVehicleRequest, - dict, -]) -def test_update_vehicle(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - 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.update_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - ) - response = client.update_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.UpdateVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -def test_update_vehicle_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 = VehicleServiceClient( - 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 = vehicle_api.UpdateVehicleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.UpdateVehicleRequest( - name='name_value', - ) - -def test_update_vehicle_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 = VehicleServiceClient( - 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.update_vehicle 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.update_vehicle] = mock_rpc - request = {} - client.update_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_vehicle(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_update_vehicle_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 = VehicleServiceAsyncClient( - 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.update_vehicle 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.update_vehicle] = mock_rpc - - request = {} - await client.update_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_vehicle(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_update_vehicle_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.UpdateVehicleRequest): - client = VehicleServiceAsyncClient( - 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.update_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - response = await client.update_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.UpdateVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicles.Vehicle) - assert response.name == 'name_value' - assert response.vehicle_state == vehicles.VehicleState.OFFLINE - assert response.supported_trip_types == [fleetengine.TripType.SHARED] - assert response.current_trips == ['current_trips_value'] - assert response.maximum_capacity == 1707 - assert response.current_route_segment == 'current_route_segment_value' - assert response.back_to_back_enabled is True - assert response.navigation_status == fleetengine.NavigationStatus.NO_GUIDANCE - - -@pytest.mark.asyncio -async def test_update_vehicle_async_from_dict(): - await test_update_vehicle_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - vehicle_api.UpdateVehicleAttributesRequest, - dict, -]) -def test_update_vehicle_attributes(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - 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.update_vehicle_attributes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicle_api.UpdateVehicleAttributesResponse( - ) - response = client.update_vehicle_attributes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.UpdateVehicleAttributesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicle_api.UpdateVehicleAttributesResponse) - - -def test_update_vehicle_attributes_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 = VehicleServiceClient( - 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 = vehicle_api.UpdateVehicleAttributesRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_attributes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_vehicle_attributes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.UpdateVehicleAttributesRequest( - name='name_value', - ) - -def test_update_vehicle_attributes_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 = VehicleServiceClient( - 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.update_vehicle_attributes 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.update_vehicle_attributes] = mock_rpc - request = {} - client.update_vehicle_attributes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_vehicle_attributes(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_update_vehicle_attributes_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 = VehicleServiceAsyncClient( - 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.update_vehicle_attributes 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.update_vehicle_attributes] = mock_rpc - - request = {} - await client.update_vehicle_attributes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_vehicle_attributes(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_update_vehicle_attributes_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.UpdateVehicleAttributesRequest): - client = VehicleServiceAsyncClient( - 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.update_vehicle_attributes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( - )) - response = await client.update_vehicle_attributes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.UpdateVehicleAttributesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicle_api.UpdateVehicleAttributesResponse) - - -@pytest.mark.asyncio -async def test_update_vehicle_attributes_async_from_dict(): - await test_update_vehicle_attributes_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - vehicle_api.ListVehiclesRequest, - dict, -]) -def test_list_vehicles(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - 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.list_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicle_api.ListVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.ListVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVehiclesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_vehicles_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 = VehicleServiceClient( - 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 = vehicle_api.ListVehiclesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_vehicles(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.ListVehiclesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - -def test_list_vehicles_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 = VehicleServiceClient( - 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.list_vehicles 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.list_vehicles] = mock_rpc - request = {} - client.list_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_vehicles(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_list_vehicles_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 = VehicleServiceAsyncClient( - 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.list_vehicles 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.list_vehicles] = mock_rpc - - request = {} - await client.list_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_vehicles(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_list_vehicles_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.ListVehiclesRequest): - client = VehicleServiceAsyncClient( - 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.list_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.ListVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVehiclesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_vehicles_async_from_dict(): - await test_list_vehicles_async(request_type=dict) - - -def test_list_vehicles_pager(transport_name: str = "grpc"): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - next_page_token='abc', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[], - next_page_token='def', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - ], - next_page_token='ghi', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_vehicles(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, vehicles.Vehicle) - for i in results) -def test_list_vehicles_pages(transport_name: str = "grpc"): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - next_page_token='abc', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[], - next_page_token='def', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - ], - next_page_token='ghi', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - ), - RuntimeError, - ) - pages = list(client.list_vehicles(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_vehicles_async_pager(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - next_page_token='abc', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[], - next_page_token='def', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - ], - next_page_token='ghi', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_vehicles(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, vehicles.Vehicle) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_vehicles_async_pages(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - next_page_token='abc', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[], - next_page_token='def', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - ], - next_page_token='ghi', - ), - vehicle_api.ListVehiclesResponse( - vehicles=[ - vehicles.Vehicle(), - vehicles.Vehicle(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_vehicles(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - vehicle_api.SearchVehiclesRequest, - dict, -]) -def test_search_vehicles(request_type, transport: str = 'grpc'): - client = VehicleServiceClient( - 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.search_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = vehicle_api.SearchVehiclesResponse( - ) - response = client.search_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.SearchVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicle_api.SearchVehiclesResponse) - - -def test_search_vehicles_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 = VehicleServiceClient( - 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 = vehicle_api.SearchVehiclesRequest( - parent='parent_value', - trip_id='trip_id_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_vehicles), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.search_vehicles(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.SearchVehiclesRequest( - parent='parent_value', - trip_id='trip_id_value', - filter='filter_value', - ) - -def test_search_vehicles_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 = VehicleServiceClient( - 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.search_vehicles 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.search_vehicles] = mock_rpc - request = {} - client.search_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_vehicles(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_search_vehicles_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 = VehicleServiceAsyncClient( - 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.search_vehicles 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.search_vehicles] = mock_rpc - - request = {} - await client.search_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.search_vehicles(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_search_vehicles_async(transport: str = 'grpc_asyncio', request_type=vehicle_api.SearchVehiclesRequest): - client = VehicleServiceAsyncClient( - 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.search_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( - )) - response = await client.search_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.SearchVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicle_api.SearchVehiclesResponse) - - -@pytest.mark.asyncio -async def test_search_vehicles_async_from_dict(): - await test_search_vehicles_async(request_type=dict) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VehicleServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = VehicleServiceClient( - 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 = VehicleServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VehicleServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = VehicleServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.VehicleServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.VehicleServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.VehicleServiceGrpcTransport, - transports.VehicleServiceGrpcAsyncIOTransport, -]) -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 = VehicleServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = VehicleServiceClient( - 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_create_vehicle_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.create_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.CreateVehicleRequest() - - 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_get_vehicle_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.get_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.GetVehicleRequest() - - 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_update_vehicle_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.update_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleRequest() - - 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_update_vehicle_attributes_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_attributes), - '__call__') as call: - call.return_value = vehicle_api.UpdateVehicleAttributesResponse() - client.update_vehicle_attributes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleAttributesRequest() - - 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_list_vehicles_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - call.return_value = vehicle_api.ListVehiclesResponse() - client.list_vehicles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.ListVehiclesRequest() - - 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_search_vehicles_empty_call_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_vehicles), - '__call__') as call: - call.return_value = vehicle_api.SearchVehiclesResponse() - client.search_vehicles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.SearchVehiclesRequest() - - assert args[0] == request_msg - - -def test_create_vehicle_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.create_vehicle(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.CreateVehicleRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_get_vehicle_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.get_vehicle(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.GetVehicleRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_update_vehicle_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle), - '__call__') as call: - call.return_value = vehicles.Vehicle() - client.update_vehicle(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_update_vehicle_attributes_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_attributes), - '__call__') as call: - call.return_value = vehicle_api.UpdateVehicleAttributesResponse() - client.update_vehicle_attributes(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleAttributesRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_list_vehicles_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - call.return_value = vehicle_api.ListVehiclesResponse() - client.list_vehicles(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.ListVehiclesRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -def test_search_vehicles_routing_parameters_request_1_grpc(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_vehicles), - '__call__') as call: - call.return_value = vehicle_api.SearchVehiclesResponse() - client.search_vehicles(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.SearchVehiclesRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_kind_grpc_asyncio(): - transport = VehicleServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = VehicleServiceAsyncClient( - 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_create_vehicle_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.create_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.CreateVehicleRequest() - - 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_get_vehicle_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.get_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.GetVehicleRequest() - - 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_update_vehicle_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.update_vehicle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleRequest() - - 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_update_vehicle_attributes_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_attributes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( - )) - await client.update_vehicle_attributes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleAttributesRequest() - - 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_list_vehicles_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_vehicles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.ListVehiclesRequest() - - 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_search_vehicles_empty_call_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( - )) - await client.search_vehicles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = vehicle_api.SearchVehiclesRequest() - - assert args[0] == request_msg - - -@pytest.mark.asyncio -async def test_create_vehicle_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.create_vehicle(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.CreateVehicleRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_get_vehicle_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.get_vehicle(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.GetVehicleRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_update_vehicle_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicles.Vehicle( - name='name_value', - vehicle_state=vehicles.VehicleState.OFFLINE, - supported_trip_types=[fleetengine.TripType.SHARED], - current_trips=['current_trips_value'], - maximum_capacity=1707, - current_route_segment='current_route_segment_value', - back_to_back_enabled=True, - navigation_status=fleetengine.NavigationStatus.NO_GUIDANCE, - )) - await client.update_vehicle(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_update_vehicle_attributes_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_attributes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.UpdateVehicleAttributesResponse( - )) - await client.update_vehicle_attributes(request={"name": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.UpdateVehicleAttributesRequest(**{"name": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_list_vehicles_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.ListVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_vehicles(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.ListVehiclesRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - -@pytest.mark.asyncio -async def test_search_vehicles_routing_parameters_request_1_grpc_asyncio(): - client = VehicleServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(vehicle_api.SearchVehiclesResponse( - )) - await client.search_vehicles(request={"parent": "providers/sample1"}) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, kw = call.mock_calls[0] - request_msg = vehicle_api.SearchVehiclesRequest(**{"parent": "providers/sample1"}) - - assert args[0] == request_msg - - expected_headers = {'provider_id': 'providers/sample1'} - assert gapic_v1.routing_header.to_grpc_metadata(expected_headers) in kw['metadata'] - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.VehicleServiceGrpcTransport, - ) - -def test_vehicle_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.VehicleServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_vehicle_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.VehicleServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_vehicle', - 'get_vehicle', - 'update_vehicle', - 'update_vehicle_attributes', - 'list_vehicles', - 'search_vehicles', - ) - 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_vehicle_service_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.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VehicleServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_vehicle_service_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.fleetengine_v1.services.vehicle_service.transports.VehicleServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VehicleServiceTransport() - adc.assert_called_once() - - -def test_vehicle_service_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) - VehicleServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VehicleServiceGrpcTransport, - transports.VehicleServiceGrpcAsyncIOTransport, - ], -) -def test_vehicle_service_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=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.VehicleServiceGrpcTransport, - transports.VehicleServiceGrpcAsyncIOTransport, - ], -) -def test_vehicle_service_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.VehicleServiceGrpcTransport, grpc_helpers), - (transports.VehicleServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_vehicle_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "fleetengine.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="fleetengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) -def test_vehicle_service_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 - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_vehicle_service_host_no_port(transport_name): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'fleetengine.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_vehicle_service_host_with_port(transport_name): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='fleetengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'fleetengine.googleapis.com:8000' - ) - -def test_vehicle_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VehicleServiceGrpcTransport( - 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_vehicle_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.VehicleServiceGrpcAsyncIOTransport( - 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.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) -def test_vehicle_service_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.VehicleServiceGrpcTransport, transports.VehicleServiceGrpcAsyncIOTransport]) -def test_vehicle_service_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_vehicle_path(): - provider = "squid" - vehicle = "clam" - expected = "providers/{provider}/vehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) - actual = VehicleServiceClient.vehicle_path(provider, vehicle) - assert expected == actual - - -def test_parse_vehicle_path(): - expected = { - "provider": "whelk", - "vehicle": "octopus", - } - path = VehicleServiceClient.vehicle_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.parse_vehicle_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = VehicleServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = VehicleServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = VehicleServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = VehicleServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = VehicleServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = VehicleServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = VehicleServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = VehicleServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = VehicleServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = VehicleServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = VehicleServiceClient.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.VehicleServiceTransport, '_prep_wrapped_messages') as prep: - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.VehicleServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = VehicleServiceClient.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 = VehicleServiceClient( - 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 = VehicleServiceAsyncClient( - 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_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = VehicleServiceClient( - 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", [ - (VehicleServiceClient, transports.VehicleServiceGrpcTransport), - (VehicleServiceAsyncClient, transports.VehicleServiceGrpcAsyncIOTransport), -]) -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-fleetengine/google/maps/fleetengine/gapic_version.py b/packages/google-maps-fleetengine/google/maps/fleetengine/gapic_version.py index 668eac0d72ce..558c8aab67c5 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine/gapic_version.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/gapic_version.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/gapic_version.py index 668eac0d72ce..558c8aab67c5 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/gapic_version.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.4" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/vehicle_api.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/vehicle_api.py index 6c9de4b52788..c08306a29ed4 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/vehicle_api.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/vehicle_api.py @@ -946,14 +946,11 @@ class VehicleMatch(proto.Message): vehicle_match_type (google.maps.fleetengine_v1.types.VehicleMatch.VehicleMatchType): Type of the vehicle match. requested_ordered_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): - The order requested for sorting vehicle - matches. + The order requested for sorting vehicle matches. Equivalent + to ``ordered_by``. ordered_by (google.maps.fleetengine_v1.types.SearchVehiclesRequest.VehicleMatchOrder): - The actual order that was used for this vehicle. Normally - this will match the 'order_by' field from the request; - however, in certain circumstances such as an internal server - error, a different method may be used (such as - ``PICKUP_POINT_STRAIGHT_DISTANCE``). + The order requested for sorting vehicle matches. Equivalent + to ``requested_ordered_by``. """ class VehicleMatchType(proto.Enum): diff --git a/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json b/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json index 23e34fbed95d..b0139d358773 100644 --- a/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json +++ b/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-fleetengine", - "version": "0.2.4" + "version": "0.1.0" }, "snippets": [ {