From f5ec5257aa61106a9487963526e7b1fb444c0b9c Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 6 Sep 2024 02:00:10 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20post-p?= =?UTF-8?q?rocessor?= 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 --- .../v1/.coveragerc | 13 - .../v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/conf.py | 376 - .../delivery_service.rst | 10 - .../fleetengine_delivery_v1/services_.rst | 6 - .../docs/fleetengine_delivery_v1/types_.rst | 6 - .../v1/docs/index.rst | 7 - .../maps/fleetengine_delivery/__init__.py | 81 - .../fleetengine_delivery/gapic_version.py | 16 - .../google/maps/fleetengine_delivery/py.typed | 2 - .../maps/fleetengine_delivery_v1/__init__.py | 82 - .../gapic_metadata.json | 178 - .../fleetengine_delivery_v1/gapic_version.py | 16 - .../maps/fleetengine_delivery_v1/py.typed | 2 - .../services/__init__.py | 15 - .../services/delivery_service/__init__.py | 22 - .../services/delivery_service/async_client.py | 1518 --- .../services/delivery_service/client.py | 1924 ---- .../services/delivery_service/pagers.py | 299 - .../delivery_service/transports/__init__.py | 38 - .../delivery_service/transports/base.py | 373 - .../delivery_service/transports/grpc.py | 516 - .../transports/grpc_asyncio.py | 661 -- .../delivery_service/transports/rest.py | 1403 --- .../fleetengine_delivery_v1/types/__init__.py | 84 - .../fleetengine_delivery_v1/types/common.py | 471 - .../types/delivery_api.py | 603 -- .../types/delivery_vehicles.py | 414 - .../fleetengine_delivery_v1/types/header.py | 168 - .../types/task_tracking_info.py | 166 - .../fleetengine_delivery_v1/types/tasks.py | 473 - .../v1/mypy.ini | 3 - .../v1/noxfile.py | 278 - ...livery_service_batch_create_tasks_async.py | 59 - ...elivery_service_batch_create_tasks_sync.py | 59 - ...y_service_create_delivery_vehicle_async.py | 53 - ...ry_service_create_delivery_vehicle_sync.py | 53 - ...ated_delivery_service_create_task_async.py | 58 - ...rated_delivery_service_create_task_sync.py | 58 - ...very_service_get_delivery_vehicle_async.py | 52 - ...ivery_service_get_delivery_vehicle_sync.py | 52 - ...nerated_delivery_service_get_task_async.py | 52 - ...enerated_delivery_service_get_task_sync.py | 52 - ...ry_service_get_task_tracking_info_async.py | 52 - ...ery_service_get_task_tracking_info_sync.py | 52 - ...ry_service_list_delivery_vehicles_async.py | 53 - ...ery_service_list_delivery_vehicles_sync.py | 53 - ...rated_delivery_service_list_tasks_async.py | 53 - ...erated_delivery_service_list_tasks_sync.py | 53 - ...y_service_update_delivery_vehicle_async.py | 51 - ...ry_service_update_delivery_vehicle_sync.py | 51 - ...ated_delivery_service_update_task_async.py | 56 - ...rated_delivery_service_update_task_sync.py | 56 - ...metadata_maps.fleetengine.delivery.v1.json | 1665 ---- .../fixup_fleetengine_delivery_v1_keywords.py | 185 - .../v1/setup.py | 94 - .../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.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 - .../gapic/fleetengine_delivery_v1/__init__.py | 16 - .../test_delivery_service.py | 8277 ----------------- .../types/delivery_api.py | 2 +- 71 files changed, 1 insertion(+), 21721 deletions(-) delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/.coveragerc delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/.flake8 delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/py.typed delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/header.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/mypy.ini delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/noxfile.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_async.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_sync.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/setup.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/.coveragerc b/owl-bot-staging/google-maps-fleetengine-delivery/v1/.coveragerc deleted file mode 100644 index 4d78db33eace..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/fleetengine_delivery/__init__.py - google/maps/fleetengine_delivery/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-delivery/v1/.flake8 b/owl-bot-staging/google-maps-fleetengine-delivery/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/MANIFEST.in b/owl-bot-staging/google-maps-fleetengine-delivery/v1/MANIFEST.in deleted file mode 100644 index 76734494c81d..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/fleetengine_delivery *.py -recursive-include google/maps/fleetengine_delivery_v1 *.py diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst deleted file mode 100644 index 1261668cfc0b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Fleetengine Delivery 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 Delivery 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-delivery/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/docs/conf.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/conf.py deleted file mode 100644 index ba785733498b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery 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-delivery" -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-delivery-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-delivery.tex", - u"google-maps-fleetengine-delivery 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-delivery", - u"Google Maps Fleetengine Delivery 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-delivery", - u"google-maps-fleetengine-delivery Documentation", - author, - "google-maps-fleetengine-delivery", - "GAPIC library for Google Maps Fleetengine Delivery 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-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst deleted file mode 100644 index 88aac9c4fbb4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/delivery_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DeliveryService ---------------------------------- - -.. automodule:: google.maps.fleetengine_delivery_v1.services.delivery_service - :members: - :inherited-members: - -.. automodule:: google.maps.fleetengine_delivery_v1.services.delivery_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst deleted file mode 100644 index 97febb72086f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Fleetengine Delivery v1 API -==================================================== -.. toctree:: - :maxdepth: 2 - - delivery_service diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst deleted file mode 100644 index d633ae8b217f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/fleetengine_delivery_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Fleetengine Delivery v1 API -================================================= - -.. automodule:: google.maps.fleetengine_delivery_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst b/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst deleted file mode 100644 index 7c5b055dd7bc..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - fleetengine_delivery_v1/services - fleetengine_delivery_v1/types diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__init__.py deleted file mode 100644 index 9aceee6293a4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/__init__.py +++ /dev/null @@ -1,81 +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_delivery import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.fleetengine_delivery_v1.services.delivery_service.client import DeliveryServiceClient -from google.maps.fleetengine_delivery_v1.services.delivery_service.async_client import DeliveryServiceAsyncClient - -from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleAttribute -from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleLocation -from google.maps.fleetengine_delivery_v1.types.common import TaskAttribute -from google.maps.fleetengine_delivery_v1.types.common import TimeWindow -from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleLocationSensor -from google.maps.fleetengine_delivery_v1.types.common import DeliveryVehicleNavigationStatus -from google.maps.fleetengine_delivery_v1.types.delivery_api import BatchCreateTasksRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import BatchCreateTasksResponse -from google.maps.fleetengine_delivery_v1.types.delivery_api import CreateDeliveryVehicleRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import CreateTaskRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import GetDeliveryVehicleRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import GetTaskRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import GetTaskTrackingInfoRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import ListDeliveryVehiclesRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import ListDeliveryVehiclesResponse -from google.maps.fleetengine_delivery_v1.types.delivery_api import ListTasksRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import ListTasksResponse -from google.maps.fleetengine_delivery_v1.types.delivery_api import UpdateDeliveryVehicleRequest -from google.maps.fleetengine_delivery_v1.types.delivery_api import UpdateTaskRequest -from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import DeliveryVehicle -from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import LocationInfo -from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import VehicleJourneySegment -from google.maps.fleetengine_delivery_v1.types.delivery_vehicles import VehicleStop -from google.maps.fleetengine_delivery_v1.types.header import DeliveryRequestHeader -from google.maps.fleetengine_delivery_v1.types.task_tracking_info import TaskTrackingInfo -from google.maps.fleetengine_delivery_v1.types.tasks import Task -from google.maps.fleetengine_delivery_v1.types.tasks import TaskTrackingViewConfig - -__all__ = ('DeliveryServiceClient', - 'DeliveryServiceAsyncClient', - 'DeliveryVehicleAttribute', - 'DeliveryVehicleLocation', - 'TaskAttribute', - 'TimeWindow', - 'DeliveryVehicleLocationSensor', - 'DeliveryVehicleNavigationStatus', - 'BatchCreateTasksRequest', - 'BatchCreateTasksResponse', - 'CreateDeliveryVehicleRequest', - 'CreateTaskRequest', - 'GetDeliveryVehicleRequest', - 'GetTaskRequest', - 'GetTaskTrackingInfoRequest', - 'ListDeliveryVehiclesRequest', - 'ListDeliveryVehiclesResponse', - 'ListTasksRequest', - 'ListTasksResponse', - 'UpdateDeliveryVehicleRequest', - 'UpdateTaskRequest', - 'DeliveryVehicle', - 'LocationInfo', - 'VehicleJourneySegment', - 'VehicleStop', - 'DeliveryRequestHeader', - 'TaskTrackingInfo', - 'Task', - 'TaskTrackingViewConfig', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/gapic_version.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/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-delivery/v1/google/maps/fleetengine_delivery/py.typed b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/py.typed deleted file mode 100644 index 8464ee4c8285..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-fleetengine-delivery package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/__init__.py deleted file mode 100644 index 3dee9f0b3f48..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/__init__.py +++ /dev/null @@ -1,82 +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_delivery_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.delivery_service import DeliveryServiceClient -from .services.delivery_service import DeliveryServiceAsyncClient - -from .types.common import DeliveryVehicleAttribute -from .types.common import DeliveryVehicleLocation -from .types.common import TaskAttribute -from .types.common import TimeWindow -from .types.common import DeliveryVehicleLocationSensor -from .types.common import DeliveryVehicleNavigationStatus -from .types.delivery_api import BatchCreateTasksRequest -from .types.delivery_api import BatchCreateTasksResponse -from .types.delivery_api import CreateDeliveryVehicleRequest -from .types.delivery_api import CreateTaskRequest -from .types.delivery_api import GetDeliveryVehicleRequest -from .types.delivery_api import GetTaskRequest -from .types.delivery_api import GetTaskTrackingInfoRequest -from .types.delivery_api import ListDeliveryVehiclesRequest -from .types.delivery_api import ListDeliveryVehiclesResponse -from .types.delivery_api import ListTasksRequest -from .types.delivery_api import ListTasksResponse -from .types.delivery_api import UpdateDeliveryVehicleRequest -from .types.delivery_api import UpdateTaskRequest -from .types.delivery_vehicles import DeliveryVehicle -from .types.delivery_vehicles import LocationInfo -from .types.delivery_vehicles import VehicleJourneySegment -from .types.delivery_vehicles import VehicleStop -from .types.header import DeliveryRequestHeader -from .types.task_tracking_info import TaskTrackingInfo -from .types.tasks import Task -from .types.tasks import TaskTrackingViewConfig - -__all__ = ( - 'DeliveryServiceAsyncClient', -'BatchCreateTasksRequest', -'BatchCreateTasksResponse', -'CreateDeliveryVehicleRequest', -'CreateTaskRequest', -'DeliveryRequestHeader', -'DeliveryServiceClient', -'DeliveryVehicle', -'DeliveryVehicleAttribute', -'DeliveryVehicleLocation', -'DeliveryVehicleLocationSensor', -'DeliveryVehicleNavigationStatus', -'GetDeliveryVehicleRequest', -'GetTaskRequest', -'GetTaskTrackingInfoRequest', -'ListDeliveryVehiclesRequest', -'ListDeliveryVehiclesResponse', -'ListTasksRequest', -'ListTasksResponse', -'LocationInfo', -'Task', -'TaskAttribute', -'TaskTrackingInfo', -'TaskTrackingViewConfig', -'TimeWindow', -'UpdateDeliveryVehicleRequest', -'UpdateTaskRequest', -'VehicleJourneySegment', -'VehicleStop', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json deleted file mode 100644 index 8b15810ecafd..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_metadata.json +++ /dev/null @@ -1,178 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.fleetengine_delivery_v1", - "protoPackage": "maps.fleetengine.delivery.v1", - "schema": "1.0", - "services": { - "DeliveryService": { - "clients": { - "grpc": { - "libraryClient": "DeliveryServiceClient", - "rpcs": { - "BatchCreateTasks": { - "methods": [ - "batch_create_tasks" - ] - }, - "CreateDeliveryVehicle": { - "methods": [ - "create_delivery_vehicle" - ] - }, - "CreateTask": { - "methods": [ - "create_task" - ] - }, - "GetDeliveryVehicle": { - "methods": [ - "get_delivery_vehicle" - ] - }, - "GetTask": { - "methods": [ - "get_task" - ] - }, - "GetTaskTrackingInfo": { - "methods": [ - "get_task_tracking_info" - ] - }, - "ListDeliveryVehicles": { - "methods": [ - "list_delivery_vehicles" - ] - }, - "ListTasks": { - "methods": [ - "list_tasks" - ] - }, - "UpdateDeliveryVehicle": { - "methods": [ - "update_delivery_vehicle" - ] - }, - "UpdateTask": { - "methods": [ - "update_task" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DeliveryServiceAsyncClient", - "rpcs": { - "BatchCreateTasks": { - "methods": [ - "batch_create_tasks" - ] - }, - "CreateDeliveryVehicle": { - "methods": [ - "create_delivery_vehicle" - ] - }, - "CreateTask": { - "methods": [ - "create_task" - ] - }, - "GetDeliveryVehicle": { - "methods": [ - "get_delivery_vehicle" - ] - }, - "GetTask": { - "methods": [ - "get_task" - ] - }, - "GetTaskTrackingInfo": { - "methods": [ - "get_task_tracking_info" - ] - }, - "ListDeliveryVehicles": { - "methods": [ - "list_delivery_vehicles" - ] - }, - "ListTasks": { - "methods": [ - "list_tasks" - ] - }, - "UpdateDeliveryVehicle": { - "methods": [ - "update_delivery_vehicle" - ] - }, - "UpdateTask": { - "methods": [ - "update_task" - ] - } - } - }, - "rest": { - "libraryClient": "DeliveryServiceClient", - "rpcs": { - "BatchCreateTasks": { - "methods": [ - "batch_create_tasks" - ] - }, - "CreateDeliveryVehicle": { - "methods": [ - "create_delivery_vehicle" - ] - }, - "CreateTask": { - "methods": [ - "create_task" - ] - }, - "GetDeliveryVehicle": { - "methods": [ - "get_delivery_vehicle" - ] - }, - "GetTask": { - "methods": [ - "get_task" - ] - }, - "GetTaskTrackingInfo": { - "methods": [ - "get_task_tracking_info" - ] - }, - "ListDeliveryVehicles": { - "methods": [ - "list_delivery_vehicles" - ] - }, - "ListTasks": { - "methods": [ - "list_tasks" - ] - }, - "UpdateDeliveryVehicle": { - "methods": [ - "update_delivery_vehicle" - ] - }, - "UpdateTask": { - "methods": [ - "update_task" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_version.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_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-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed deleted file mode 100644 index 8464ee4c8285..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-fleetengine-delivery package uses inline types. diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_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-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/__init__.py deleted file mode 100644 index 4dc5b334d96a..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_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 DeliveryServiceClient -from .async_client import DeliveryServiceAsyncClient - -__all__ = ( - 'DeliveryServiceClient', - 'DeliveryServiceAsyncClient', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py deleted file mode 100644 index 31bcbc28cfc2..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py +++ /dev/null @@ -1,1518 +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_delivery_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_delivery_v1.services.delivery_service import pagers -from google.maps.fleetengine_delivery_v1.types import common -from google.maps.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks -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 -from .transports.base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DeliveryServiceGrpcAsyncIOTransport -from .client import DeliveryServiceClient - - -class DeliveryServiceAsyncClient: - """The Last Mile Delivery service.""" - - _client: DeliveryServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = DeliveryServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = DeliveryServiceClient._DEFAULT_UNIVERSE - - delivery_vehicle_path = staticmethod(DeliveryServiceClient.delivery_vehicle_path) - parse_delivery_vehicle_path = staticmethod(DeliveryServiceClient.parse_delivery_vehicle_path) - task_path = staticmethod(DeliveryServiceClient.task_path) - parse_task_path = staticmethod(DeliveryServiceClient.parse_task_path) - task_tracking_info_path = staticmethod(DeliveryServiceClient.task_tracking_info_path) - parse_task_tracking_info_path = staticmethod(DeliveryServiceClient.parse_task_tracking_info_path) - common_billing_account_path = staticmethod(DeliveryServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DeliveryServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DeliveryServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DeliveryServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DeliveryServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DeliveryServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DeliveryServiceClient.common_project_path) - parse_common_project_path = staticmethod(DeliveryServiceClient.parse_common_project_path) - common_location_path = staticmethod(DeliveryServiceClient.common_location_path) - parse_common_location_path = staticmethod(DeliveryServiceClient.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: - DeliveryServiceAsyncClient: The constructed client. - """ - return DeliveryServiceClient.from_service_account_info.__func__(DeliveryServiceAsyncClient, 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: - DeliveryServiceAsyncClient: The constructed client. - """ - return DeliveryServiceClient.from_service_account_file.__func__(DeliveryServiceAsyncClient, 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 DeliveryServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DeliveryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DeliveryServiceTransport: 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 = DeliveryServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DeliveryServiceTransport, Callable[..., DeliveryServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the delivery 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,DeliveryServiceTransport,Callable[..., DeliveryServiceTransport]]]): - 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 DeliveryServiceTransport 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 = DeliveryServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_delivery_vehicle(self, - request: Optional[Union[delivery_api.CreateDeliveryVehicleRequest, dict]] = None, - *, - parent: Optional[str] = None, - delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = None, - delivery_vehicle_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Creates and returns a new ``DeliveryVehicle``. - - .. 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_delivery_v1 - - async def sample_create_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( - parent="parent_value", - delivery_vehicle_id="delivery_vehicle_id_value", - ) - - # Make the request - response = await client.create_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest, dict]]): - The request object. The ``CreateDeliveryVehicle`` request message. - parent (:class:`str`): - Required. Must be in the format - ``providers/{provider}``. The provider must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - delivery_vehicle (:class:`google.maps.fleetengine_delivery_v1.types.DeliveryVehicle`): - Required. The ``DeliveryVehicle`` entity to create. When - creating a new delivery vehicle, you may set the - following optional fields: - - - type - - last_location - - attributes - - Note: The DeliveryVehicle's ``name`` field is ignored. - All other DeliveryVehicle fields must not be set; - otherwise, an error is returned. - - This corresponds to the ``delivery_vehicle`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - delivery_vehicle_id (:class:`str`): - Required. The Delivery Vehicle ID must be unique and - 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 '#'. - - This corresponds to the ``delivery_vehicle_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, delivery_vehicle, delivery_vehicle_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, delivery_api.CreateDeliveryVehicleRequest): - request = delivery_api.CreateDeliveryVehicleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if delivery_vehicle is not None: - request.delivery_vehicle = delivery_vehicle - if delivery_vehicle_id is not None: - request.delivery_vehicle_id = delivery_vehicle_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_delivery_vehicle] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # 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_delivery_vehicle(self, - request: Optional[Union[delivery_api.GetDeliveryVehicleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Returns the specified ``DeliveryVehicle`` instance. - - .. 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_delivery_v1 - - async def sample_get_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest, dict]]): - The request object. The ``GetDeliveryVehicle`` request message. - name (:class:`str`): - Required. Must be in the format - ``providers/{provider}/deliveryVehicles/{delivery_vehicle}``. - The ``provider`` must be the Google Cloud Project ID. - For example, ``sample-cloud-project``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, delivery_api.GetDeliveryVehicleRequest): - request = delivery_api.GetDeliveryVehicleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_delivery_vehicle] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # 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_delivery_vehicle(self, - request: Optional[Union[delivery_api.UpdateDeliveryVehicleRequest, dict]] = None, - *, - delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Writes updated ``DeliveryVehicle`` data to Fleet Engine, and - assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update - the name of the ``DeliveryVehicle``. You *can* update - ``remaining_vehicle_journey_segments``, but it must contain all - of the ``VehicleJourneySegment``\ s to be persisted on the - ``DeliveryVehicle``. The ``task_id``\ s are retrieved from - ``remaining_vehicle_journey_segments``, and their corresponding - ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have - not yet been assigned. - - .. 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_delivery_v1 - - async def sample_update_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( - ) - - # Make the request - response = await client.update_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest, dict]]): - The request object. The ``UpdateDeliveryVehicle`` request message. - delivery_vehicle (:class:`google.maps.fleetengine_delivery_v1.types.DeliveryVehicle`): - Required. The ``DeliveryVehicle`` entity update to - apply. Note: You cannot update the name of the - ``DeliveryVehicle``. - - This corresponds to the ``delivery_vehicle`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. A field mask that indicates which - ``DeliveryVehicle`` fields to update. Note that the - update_mask must contain at least one field. - - This is a comma-separated list of fully qualified names - of fields. Example: - ``"remaining_vehicle_journey_segments"``. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([delivery_vehicle, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, delivery_api.UpdateDeliveryVehicleRequest): - request = delivery_api.UpdateDeliveryVehicleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if delivery_vehicle is not None: - request.delivery_vehicle = delivery_vehicle - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_delivery_vehicle] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("delivery_vehicle.name", request.delivery_vehicle.name), - )), - ) - - # 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 batch_create_tasks(self, - request: Optional[Union[delivery_api.BatchCreateTasksRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_api.BatchCreateTasksResponse: - r"""Creates and returns a batch of new ``Task`` objects. - - .. 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_delivery_v1 - - async def sample_batch_create_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - requests = fleetengine_delivery_v1.CreateTaskRequest() - requests.parent = "parent_value" - requests.task_id = "task_id_value" - requests.task.type_ = "UNAVAILABLE" - requests.task.state = "CLOSED" - - request = fleetengine_delivery_v1.BatchCreateTasksRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_tasks(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest, dict]]): - The request object. The ``BatchCreateTask`` 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_delivery_v1.types.BatchCreateTasksResponse: - The BatchCreateTask 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, delivery_api.BatchCreateTasksRequest): - request = delivery_api.BatchCreateTasksRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.batch_create_tasks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # 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 create_task(self, - request: Optional[Union[delivery_api.CreateTaskRequest, dict]] = None, - *, - parent: Optional[str] = None, - task: Optional[tasks.Task] = None, - task_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tasks.Task: - r"""Creates and returns a new ``Task`` object. - - .. 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_delivery_v1 - - async def sample_create_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.CreateTaskRequest( - parent="parent_value", - task_id="task_id_value", - task=task, - ) - - # Make the request - response = await client.create_task(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.CreateTaskRequest, dict]]): - The request object. The ``CreateTask`` request message. - parent (:class:`str`): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - task (:class:`google.maps.fleetengine_delivery_v1.types.Task`): - Required. The Task entity to create. When creating a - Task, the following fields are required: - - - ``type`` - - ``state`` (must be set to ``OPEN``) - - ``tracking_id`` (must not be set for ``UNAVAILABLE`` - or ``SCHEDULED_STOP`` tasks, but required for all - other task types) - - ``planned_location`` (optional for ``UNAVAILABLE`` - tasks) - - ``task_duration`` - - Note: The Task's ``name`` field is ignored. All other - Task fields must not be set; otherwise, an error is - returned. - - This corresponds to the ``task`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - task_id (:class:`str`): - Required. The Task ID must be unique, but it should be - not a shipment tracking ID. To store a shipment tracking - ID, use the ``tracking_id`` field. Note that multiple - tasks can have the same ``tracking_id``. Task IDs are - 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 '#'. - - This corresponds to the ``task_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, task, task_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, delivery_api.CreateTaskRequest): - request = delivery_api.CreateTaskRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if task is not None: - request.task = task - if task_id is not None: - request.task_id = task_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_task] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # 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_task(self, - request: Optional[Union[delivery_api.GetTaskRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tasks.Task: - r"""Gets information about a ``Task``. - - .. 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_delivery_v1 - - async def sample_get_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskRequest( - name="name_value", - ) - - # Make the request - response = await client.get_task(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.GetTaskRequest, dict]]): - The request object. The ``GetTask`` request message. - name (:class:`str`): - Required. Must be in the format - ``providers/{provider}/tasks/{task}``. The ``provider`` - must be the Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, delivery_api.GetTaskRequest): - request = delivery_api.GetTaskRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_task] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # 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_task(self, - request: Optional[Union[delivery_api.UpdateTaskRequest, dict]] = None, - *, - task: Optional[tasks.Task] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tasks.Task: - r"""Updates ``Task`` 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_delivery_v1 - - async def sample_update_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.UpdateTaskRequest( - task=task, - ) - - # Make the request - response = await client.update_task(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest, dict]]): - The request object. The ``UpdateTask`` request message. - task (:class:`google.maps.fleetengine_delivery_v1.types.Task`): - Required. The Task associated with the update. The - following fields are maintained by Fleet Engine. Do not - update them using ``Task.update``. - - - ``last_location``. - - ``last_location_snappable``. - - ``name``. - - ``remaining_vehicle_journey_segments``. - - ``task_outcome_location_source``. - - Note: You cannot change the value of ``task_outcome`` - once you set it. - - If the Task has been assigned to a delivery vehicle, - then don't set the Task state to CLOSED using - ``Task.update``. Instead, remove the ``VehicleStop`` - that contains the Task from the delivery vehicle, which - automatically sets the Task state to CLOSED. - - This corresponds to the ``task`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The field mask that indicates which Task - fields to update. Note: The ``update_mask`` must contain - at least one field. - - This is a comma-separated list of fully qualified names - of fields. Example: - ``"task_outcome,task_outcome_time,task_outcome_location"``. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([task, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, delivery_api.UpdateTaskRequest): - request = delivery_api.UpdateTaskRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if task is not None: - request.task = task - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_task] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("task.name", request.task.name), - )), - ) - - # 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_tasks(self, - request: Optional[Union[delivery_api.ListTasksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTasksAsyncPager: - r"""Gets all ``Task``\ s that meet the specified filtering criteria. - - .. 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_delivery_v1 - - async def sample_list_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListTasksRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tasks(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.ListTasksRequest, dict]]): - The request object. The ``ListTasks`` request message. - parent (:class:`str`): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.services.delivery_service.pagers.ListTasksAsyncPager: - The ListTasks response that contains the set of Tasks that meet the filter - criteria in the ListTasksRequest. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, delivery_api.ListTasksRequest): - request = delivery_api.ListTasksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_tasks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # 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.ListTasksAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_task_tracking_info(self, - request: Optional[Union[delivery_api.GetTaskTrackingInfoRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> task_tracking_info.TaskTrackingInfo: - r"""Returns the specified ``TaskTrackingInfo`` instance. - - .. 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_delivery_v1 - - async def sample_get_task_tracking_info(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( - name="name_value", - ) - - # Make the request - response = await client.get_task_tracking_info(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest, dict]]): - The request object. The ``GetTaskTrackingInfoRequest`` request message. - name (:class:`str`): - Required. Must be in the format - ``providers/{provider}/taskTrackingInfo/{tracking_id}``. - The ``provider`` must be the Google Cloud Project ID, - and the ``tracking_id`` must be the tracking ID - associated with the task. An example name can be - ``providers/sample-cloud-project/taskTrackingInfo/sample-tracking-id``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.TaskTrackingInfo: - The TaskTrackingInfo message. The message contains task tracking - information which will be used for display. If a - tracking ID is associated with multiple Tasks, Fleet - Engine uses a heuristic to decide which Task's - TaskTrackingInfo to select. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, delivery_api.GetTaskTrackingInfoRequest): - request = delivery_api.GetTaskTrackingInfoRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_task_tracking_info] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # 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_delivery_vehicles(self, - request: Optional[Union[delivery_api.ListDeliveryVehiclesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDeliveryVehiclesAsyncPager: - r"""Gets all ``DeliveryVehicle``\ s that meet the specified - filtering criteria. - - .. 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_delivery_v1 - - async def sample_list_delivery_vehicles(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_delivery_vehicles(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest, dict]]): - The request object. The ``ListDeliveryVehicles`` request message. - parent (:class:`str`): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesAsyncPager: - The ListDeliveryVehicles response message. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - 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, delivery_api.ListDeliveryVehiclesRequest): - request = delivery_api.ListDeliveryVehiclesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_delivery_vehicles] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # 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.ListDeliveryVehiclesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "DeliveryServiceAsyncClient": - 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__ = ( - "DeliveryServiceAsyncClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py deleted file mode 100644 index c4eae523cd1f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py +++ /dev/null @@ -1,1924 +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_delivery_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_delivery_v1.services.delivery_service import pagers -from google.maps.fleetengine_delivery_v1.types import common -from google.maps.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks -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 -from .transports.base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DeliveryServiceGrpcTransport -from .transports.grpc_asyncio import DeliveryServiceGrpcAsyncIOTransport -from .transports.rest import DeliveryServiceRestTransport - - -class DeliveryServiceClientMeta(type): - """Metaclass for the DeliveryService 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[DeliveryServiceTransport]] - _transport_registry["grpc"] = DeliveryServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DeliveryServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DeliveryServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DeliveryServiceTransport]: - """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 DeliveryServiceClient(metaclass=DeliveryServiceClientMeta): - """The Last Mile Delivery 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: - DeliveryServiceClient: 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: - DeliveryServiceClient: 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) -> DeliveryServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DeliveryServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def delivery_vehicle_path(provider: str,vehicle: str,) -> str: - """Returns a fully-qualified delivery_vehicle string.""" - return "providers/{provider}/deliveryVehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) - - @staticmethod - def parse_delivery_vehicle_path(path: str) -> Dict[str,str]: - """Parses a delivery_vehicle path into its component segments.""" - m = re.match(r"^providers/(?P.+?)/deliveryVehicles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def task_path(provider: str,task: str,) -> str: - """Returns a fully-qualified task string.""" - return "providers/{provider}/tasks/{task}".format(provider=provider, task=task, ) - - @staticmethod - def parse_task_path(path: str) -> Dict[str,str]: - """Parses a task path into its component segments.""" - m = re.match(r"^providers/(?P.+?)/tasks/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def task_tracking_info_path(provider: str,tracking: str,) -> str: - """Returns a fully-qualified task_tracking_info string.""" - return "providers/{provider}/taskTrackingInfo/{tracking}".format(provider=provider, tracking=tracking, ) - - @staticmethod - def parse_task_tracking_info_path(path: str) -> Dict[str,str]: - """Parses a task_tracking_info path into its component segments.""" - m = re.match(r"^providers/(?P.+?)/taskTrackingInfo/(?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 = DeliveryServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = DeliveryServiceClient._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 = DeliveryServiceClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = DeliveryServiceClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - DeliveryServiceClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @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, DeliveryServiceTransport, Callable[..., DeliveryServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the delivery 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,DeliveryServiceTransport,Callable[..., DeliveryServiceTransport]]]): - 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 DeliveryServiceTransport 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 = DeliveryServiceClient._read_environment_variables() - self._client_cert_source = DeliveryServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = DeliveryServiceClient._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, DeliveryServiceTransport) - if transport_provided: - # transport is a DeliveryServiceTransport 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(DeliveryServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - DeliveryServiceClient._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[DeliveryServiceTransport], Callable[..., DeliveryServiceTransport]] = ( - DeliveryServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., DeliveryServiceTransport], 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_delivery_vehicle(self, - request: Optional[Union[delivery_api.CreateDeliveryVehicleRequest, dict]] = None, - *, - parent: Optional[str] = None, - delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = None, - delivery_vehicle_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Creates and returns a new ``DeliveryVehicle``. - - .. 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_delivery_v1 - - def sample_create_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( - parent="parent_value", - delivery_vehicle_id="delivery_vehicle_id_value", - ) - - # Make the request - response = client.create_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest, dict]): - The request object. The ``CreateDeliveryVehicle`` request message. - parent (str): - Required. Must be in the format - ``providers/{provider}``. The provider must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): - Required. The ``DeliveryVehicle`` entity to create. When - creating a new delivery vehicle, you may set the - following optional fields: - - - type - - last_location - - attributes - - Note: The DeliveryVehicle's ``name`` field is ignored. - All other DeliveryVehicle fields must not be set; - otherwise, an error is returned. - - This corresponds to the ``delivery_vehicle`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - delivery_vehicle_id (str): - Required. The Delivery Vehicle ID must be unique and - 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 '#'. - - This corresponds to the ``delivery_vehicle_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, delivery_vehicle, delivery_vehicle_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, delivery_api.CreateDeliveryVehicleRequest): - request = delivery_api.CreateDeliveryVehicleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if delivery_vehicle is not None: - request.delivery_vehicle = delivery_vehicle - if delivery_vehicle_id is not None: - request.delivery_vehicle_id = delivery_vehicle_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_delivery_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_delivery_vehicle(self, - request: Optional[Union[delivery_api.GetDeliveryVehicleRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Returns the specified ``DeliveryVehicle`` instance. - - .. 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_delivery_v1 - - def sample_get_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.get_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest, dict]): - The request object. The ``GetDeliveryVehicle`` request message. - name (str): - Required. Must be in the format - ``providers/{provider}/deliveryVehicles/{delivery_vehicle}``. - The ``provider`` must be the Google Cloud Project ID. - For example, ``sample-cloud-project``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, delivery_api.GetDeliveryVehicleRequest): - request = delivery_api.GetDeliveryVehicleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_delivery_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_delivery_vehicle(self, - request: Optional[Union[delivery_api.UpdateDeliveryVehicleRequest, dict]] = None, - *, - delivery_vehicle: Optional[delivery_vehicles.DeliveryVehicle] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Writes updated ``DeliveryVehicle`` data to Fleet Engine, and - assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update - the name of the ``DeliveryVehicle``. You *can* update - ``remaining_vehicle_journey_segments``, but it must contain all - of the ``VehicleJourneySegment``\ s to be persisted on the - ``DeliveryVehicle``. The ``task_id``\ s are retrieved from - ``remaining_vehicle_journey_segments``, and their corresponding - ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have - not yet been assigned. - - .. 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_delivery_v1 - - def sample_update_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( - ) - - # Make the request - response = client.update_delivery_vehicle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest, dict]): - The request object. The ``UpdateDeliveryVehicle`` request message. - delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): - Required. The ``DeliveryVehicle`` entity update to - apply. Note: You cannot update the name of the - ``DeliveryVehicle``. - - This corresponds to the ``delivery_vehicle`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. A field mask that indicates which - ``DeliveryVehicle`` fields to update. Note that the - update_mask must contain at least one field. - - This is a comma-separated list of fully qualified names - of fields. Example: - ``"remaining_vehicle_journey_segments"``. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.DeliveryVehicle: - The DeliveryVehicle message. A delivery vehicle transports shipments from a - depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery - vehicles also transport shipments directly from the - pickup location to the delivery location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - DeliveryVehicle.current_route_segment field in the - gRPC API and the DeliveryVehicle.currentRouteSegment - field in the REST API refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([delivery_vehicle, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, delivery_api.UpdateDeliveryVehicleRequest): - request = delivery_api.UpdateDeliveryVehicleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if delivery_vehicle is not None: - request.delivery_vehicle = delivery_vehicle - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_delivery_vehicle] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.delivery_vehicle.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 batch_create_tasks(self, - request: Optional[Union[delivery_api.BatchCreateTasksRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_api.BatchCreateTasksResponse: - r"""Creates and returns a batch of new ``Task`` objects. - - .. 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_delivery_v1 - - def sample_batch_create_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - requests = fleetengine_delivery_v1.CreateTaskRequest() - requests.parent = "parent_value" - requests.task_id = "task_id_value" - requests.task.type_ = "UNAVAILABLE" - requests.task.state = "CLOSED" - - request = fleetengine_delivery_v1.BatchCreateTasksRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_tasks(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest, dict]): - The request object. The ``BatchCreateTask`` 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_delivery_v1.types.BatchCreateTasksResponse: - The BatchCreateTask 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, delivery_api.BatchCreateTasksRequest): - request = delivery_api.BatchCreateTasksRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_create_tasks] - - 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 create_task(self, - request: Optional[Union[delivery_api.CreateTaskRequest, dict]] = None, - *, - parent: Optional[str] = None, - task: Optional[tasks.Task] = None, - task_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tasks.Task: - r"""Creates and returns a new ``Task`` object. - - .. 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_delivery_v1 - - def sample_create_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.CreateTaskRequest( - parent="parent_value", - task_id="task_id_value", - task=task, - ) - - # Make the request - response = client.create_task(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.CreateTaskRequest, dict]): - The request object. The ``CreateTask`` request message. - parent (str): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - task (google.maps.fleetengine_delivery_v1.types.Task): - Required. The Task entity to create. When creating a - Task, the following fields are required: - - - ``type`` - - ``state`` (must be set to ``OPEN``) - - ``tracking_id`` (must not be set for ``UNAVAILABLE`` - or ``SCHEDULED_STOP`` tasks, but required for all - other task types) - - ``planned_location`` (optional for ``UNAVAILABLE`` - tasks) - - ``task_duration`` - - Note: The Task's ``name`` field is ignored. All other - Task fields must not be set; otherwise, an error is - returned. - - This corresponds to the ``task`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - task_id (str): - Required. The Task ID must be unique, but it should be - not a shipment tracking ID. To store a shipment tracking - ID, use the ``tracking_id`` field. Note that multiple - tasks can have the same ``tracking_id``. Task IDs are - 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 '#'. - - This corresponds to the ``task_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, task, task_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, delivery_api.CreateTaskRequest): - request = delivery_api.CreateTaskRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if task is not None: - request.task = task - if task_id is not None: - request.task_id = task_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_task] - - 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_task(self, - request: Optional[Union[delivery_api.GetTaskRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tasks.Task: - r"""Gets information about a ``Task``. - - .. 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_delivery_v1 - - def sample_get_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskRequest( - name="name_value", - ) - - # Make the request - response = client.get_task(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.GetTaskRequest, dict]): - The request object. The ``GetTask`` request message. - name (str): - Required. Must be in the format - ``providers/{provider}/tasks/{task}``. The ``provider`` - must be the Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, delivery_api.GetTaskRequest): - request = delivery_api.GetTaskRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_task] - - 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_task(self, - request: Optional[Union[delivery_api.UpdateTaskRequest, dict]] = None, - *, - task: Optional[tasks.Task] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> tasks.Task: - r"""Updates ``Task`` 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_delivery_v1 - - def sample_update_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.UpdateTaskRequest( - task=task, - ) - - # Make the request - response = client.update_task(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest, dict]): - The request object. The ``UpdateTask`` request message. - task (google.maps.fleetengine_delivery_v1.types.Task): - Required. The Task associated with the update. The - following fields are maintained by Fleet Engine. Do not - update them using ``Task.update``. - - - ``last_location``. - - ``last_location_snappable``. - - ``name``. - - ``remaining_vehicle_journey_segments``. - - ``task_outcome_location_source``. - - Note: You cannot change the value of ``task_outcome`` - once you set it. - - If the Task has been assigned to a delivery vehicle, - then don't set the Task state to CLOSED using - ``Task.update``. Instead, remove the ``VehicleStop`` - that contains the Task from the delivery vehicle, which - automatically sets the Task state to CLOSED. - - This corresponds to the ``task`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The field mask that indicates which Task - fields to update. Note: The ``update_mask`` must contain - at least one field. - - This is a comma-separated list of fully qualified names - of fields. Example: - ``"task_outcome,task_outcome_time,task_outcome_location"``. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.Task: - A Task in the Delivery API represents a single action to track. In general, - there is a distinction between shipment-related Tasks - and break Tasks. A shipment can have multiple Tasks - associated with it. For example, there could be one - Task for the pickup, and one for the drop-off or - transfer. Also, different Tasks for a given shipment - can be handled by different vehicles. For example, - one vehicle could handle the pickup, driving the - shipment to the hub, while another vehicle drives the - same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - Task.journey_sharing_info field in the gRPC API and - the Task.journeySharingInfo field in the REST API - refer to the same field. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([task, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, delivery_api.UpdateTaskRequest): - request = delivery_api.UpdateTaskRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if task is not None: - request.task = task - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_task] - - header_params = {} - - routing_param_regex = re.compile('^(?Pproviders/[^/]+)$') - regex_match = routing_param_regex.match(request.task.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_tasks(self, - request: Optional[Union[delivery_api.ListTasksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListTasksPager: - r"""Gets all ``Task``\ s that meet the specified filtering criteria. - - .. 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_delivery_v1 - - def sample_list_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListTasksRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tasks(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.ListTasksRequest, dict]): - The request object. The ``ListTasks`` request message. - parent (str): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.services.delivery_service.pagers.ListTasksPager: - The ListTasks response that contains the set of Tasks that meet the filter - criteria in the ListTasksRequest. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, delivery_api.ListTasksRequest): - request = delivery_api.ListTasksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_tasks] - - 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.ListTasksPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_task_tracking_info(self, - request: Optional[Union[delivery_api.GetTaskTrackingInfoRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> task_tracking_info.TaskTrackingInfo: - r"""Returns the specified ``TaskTrackingInfo`` instance. - - .. 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_delivery_v1 - - def sample_get_task_tracking_info(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( - name="name_value", - ) - - # Make the request - response = client.get_task_tracking_info(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest, dict]): - The request object. The ``GetTaskTrackingInfoRequest`` request message. - name (str): - Required. Must be in the format - ``providers/{provider}/taskTrackingInfo/{tracking_id}``. - The ``provider`` must be the Google Cloud Project ID, - and the ``tracking_id`` must be the tracking ID - associated with the task. An example name can be - ``providers/sample-cloud-project/taskTrackingInfo/sample-tracking-id``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.types.TaskTrackingInfo: - The TaskTrackingInfo message. The message contains task tracking - information which will be used for display. If a - tracking ID is associated with multiple Tasks, Fleet - Engine uses a heuristic to decide which Task's - TaskTrackingInfo to select. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, delivery_api.GetTaskTrackingInfoRequest): - request = delivery_api.GetTaskTrackingInfoRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_task_tracking_info] - - 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_delivery_vehicles(self, - request: Optional[Union[delivery_api.ListDeliveryVehiclesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDeliveryVehiclesPager: - r"""Gets all ``DeliveryVehicle``\ s that meet the specified - filtering criteria. - - .. 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_delivery_v1 - - def sample_list_delivery_vehicles(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_delivery_vehicles(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest, dict]): - The request object. The ``ListDeliveryVehicles`` request message. - parent (str): - Required. Must be in the format - ``providers/{provider}``. The ``provider`` must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesPager: - The ListDeliveryVehicles response message. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - 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, delivery_api.ListDeliveryVehiclesRequest): - request = delivery_api.ListDeliveryVehiclesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_delivery_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.ListDeliveryVehiclesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DeliveryServiceClient": - 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__ = ( - "DeliveryServiceClient", -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py deleted file mode 100644 index 71e6a9f33252..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py +++ /dev/null @@ -1,299 +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_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import tasks - - -class ListTasksPager: - """A pager for iterating through ``list_tasks`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` object, and - provides an ``__iter__`` method to iterate through its - ``tasks`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTasks`` requests and continue to iterate - through the ``tasks`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` - 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[..., delivery_api.ListTasksResponse], - request: delivery_api.ListTasksRequest, - response: delivery_api.ListTasksResponse, - *, - 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_delivery_v1.types.ListTasksRequest): - The initial request object. - response (google.maps.fleetengine_delivery_v1.types.ListTasksResponse): - 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 = delivery_api.ListTasksRequest(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[delivery_api.ListTasksResponse]: - 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[tasks.Task]: - for page in self.pages: - yield from page.tasks - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTasksAsyncPager: - """A pager for iterating through ``list_tasks`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``tasks`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTasks`` requests and continue to iterate - through the ``tasks`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListTasksResponse` - 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[delivery_api.ListTasksResponse]], - request: delivery_api.ListTasksRequest, - response: delivery_api.ListTasksResponse, - *, - 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_delivery_v1.types.ListTasksRequest): - The initial request object. - response (google.maps.fleetengine_delivery_v1.types.ListTasksResponse): - 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 = delivery_api.ListTasksRequest(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[delivery_api.ListTasksResponse]: - 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[tasks.Task]: - async def async_generator(): - async for page in self.pages: - for response in page.tasks: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDeliveryVehiclesPager: - """A pager for iterating through ``list_delivery_vehicles`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``delivery_vehicles`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDeliveryVehicles`` requests and continue to iterate - through the ``delivery_vehicles`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` - 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[..., delivery_api.ListDeliveryVehiclesResponse], - request: delivery_api.ListDeliveryVehiclesRequest, - response: delivery_api.ListDeliveryVehiclesResponse, - *, - 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_delivery_v1.types.ListDeliveryVehiclesRequest): - The initial request object. - response (google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse): - 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 = delivery_api.ListDeliveryVehiclesRequest(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[delivery_api.ListDeliveryVehiclesResponse]: - 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[delivery_vehicles.DeliveryVehicle]: - for page in self.pages: - yield from page.delivery_vehicles - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDeliveryVehiclesAsyncPager: - """A pager for iterating through ``list_delivery_vehicles`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``delivery_vehicles`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDeliveryVehicles`` requests and continue to iterate - through the ``delivery_vehicles`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse` - 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[delivery_api.ListDeliveryVehiclesResponse]], - request: delivery_api.ListDeliveryVehiclesRequest, - response: delivery_api.ListDeliveryVehiclesResponse, - *, - 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_delivery_v1.types.ListDeliveryVehiclesRequest): - The initial request object. - response (google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesResponse): - 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 = delivery_api.ListDeliveryVehiclesRequest(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[delivery_api.ListDeliveryVehiclesResponse]: - 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[delivery_vehicles.DeliveryVehicle]: - async def async_generator(): - async for page in self.pages: - for response in page.delivery_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-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/__init__.py deleted file mode 100644 index bdf0ae0905a7..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import DeliveryServiceTransport -from .grpc import DeliveryServiceGrpcTransport -from .grpc_asyncio import DeliveryServiceGrpcAsyncIOTransport -from .rest import DeliveryServiceRestTransport -from .rest import DeliveryServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DeliveryServiceTransport]] -_transport_registry['grpc'] = DeliveryServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DeliveryServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DeliveryServiceRestTransport - -__all__ = ( - 'DeliveryServiceTransport', - 'DeliveryServiceGrpcTransport', - 'DeliveryServiceGrpcAsyncIOTransport', - 'DeliveryServiceRestTransport', - 'DeliveryServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py deleted file mode 100644 index fba0b4384257..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py +++ /dev/null @@ -1,373 +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_delivery_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_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DeliveryServiceTransport(abc.ABC): - """Abstract transport class for DeliveryService.""" - - 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_delivery_vehicle: gapic_v1.method.wrap_method( - self.create_delivery_vehicle, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_delivery_vehicle: gapic_v1.method.wrap_method( - self.get_delivery_vehicle, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_delivery_vehicle: gapic_v1.method.wrap_method( - self.update_delivery_vehicle, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.batch_create_tasks: gapic_v1.method.wrap_method( - self.batch_create_tasks, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_task: gapic_v1.method.wrap_method( - self.create_task, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_task: gapic_v1.method.wrap_method( - self.get_task, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_task: gapic_v1.method.wrap_method( - self.update_task, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_tasks: gapic_v1.method.wrap_method( - self.list_tasks, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_task_tracking_info: gapic_v1.method.wrap_method( - self.get_task_tracking_info, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_delivery_vehicles: gapic_v1.method.wrap_method( - self.list_delivery_vehicles, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.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_delivery_vehicle(self) -> Callable[ - [delivery_api.CreateDeliveryVehicleRequest], - Union[ - delivery_vehicles.DeliveryVehicle, - Awaitable[delivery_vehicles.DeliveryVehicle] - ]]: - raise NotImplementedError() - - @property - def get_delivery_vehicle(self) -> Callable[ - [delivery_api.GetDeliveryVehicleRequest], - Union[ - delivery_vehicles.DeliveryVehicle, - Awaitable[delivery_vehicles.DeliveryVehicle] - ]]: - raise NotImplementedError() - - @property - def update_delivery_vehicle(self) -> Callable[ - [delivery_api.UpdateDeliveryVehicleRequest], - Union[ - delivery_vehicles.DeliveryVehicle, - Awaitable[delivery_vehicles.DeliveryVehicle] - ]]: - raise NotImplementedError() - - @property - def batch_create_tasks(self) -> Callable[ - [delivery_api.BatchCreateTasksRequest], - Union[ - delivery_api.BatchCreateTasksResponse, - Awaitable[delivery_api.BatchCreateTasksResponse] - ]]: - raise NotImplementedError() - - @property - def create_task(self) -> Callable[ - [delivery_api.CreateTaskRequest], - Union[ - tasks.Task, - Awaitable[tasks.Task] - ]]: - raise NotImplementedError() - - @property - def get_task(self) -> Callable[ - [delivery_api.GetTaskRequest], - Union[ - tasks.Task, - Awaitable[tasks.Task] - ]]: - raise NotImplementedError() - - @property - def update_task(self) -> Callable[ - [delivery_api.UpdateTaskRequest], - Union[ - tasks.Task, - Awaitable[tasks.Task] - ]]: - raise NotImplementedError() - - @property - def list_tasks(self) -> Callable[ - [delivery_api.ListTasksRequest], - Union[ - delivery_api.ListTasksResponse, - Awaitable[delivery_api.ListTasksResponse] - ]]: - raise NotImplementedError() - - @property - def get_task_tracking_info(self) -> Callable[ - [delivery_api.GetTaskTrackingInfoRequest], - Union[ - task_tracking_info.TaskTrackingInfo, - Awaitable[task_tracking_info.TaskTrackingInfo] - ]]: - raise NotImplementedError() - - @property - def list_delivery_vehicles(self) -> Callable[ - [delivery_api.ListDeliveryVehiclesRequest], - Union[ - delivery_api.ListDeliveryVehiclesResponse, - Awaitable[delivery_api.ListDeliveryVehiclesResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DeliveryServiceTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py deleted file mode 100644 index 03a7d345d054..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py +++ /dev/null @@ -1,516 +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_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks -from .base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO - - -class DeliveryServiceGrpcTransport(DeliveryServiceTransport): - """gRPC backend transport for DeliveryService. - - The Last Mile Delivery 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_delivery_vehicle(self) -> Callable[ - [delivery_api.CreateDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - r"""Return a callable for the create delivery vehicle method over gRPC. - - Creates and returns a new ``DeliveryVehicle``. - - Returns: - Callable[[~.CreateDeliveryVehicleRequest], - ~.DeliveryVehicle]: - 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_delivery_vehicle' not in self._stubs: - self._stubs['create_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/CreateDeliveryVehicle', - request_serializer=delivery_api.CreateDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['create_delivery_vehicle'] - - @property - def get_delivery_vehicle(self) -> Callable[ - [delivery_api.GetDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - r"""Return a callable for the get delivery vehicle method over gRPC. - - Returns the specified ``DeliveryVehicle`` instance. - - Returns: - Callable[[~.GetDeliveryVehicleRequest], - ~.DeliveryVehicle]: - 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_delivery_vehicle' not in self._stubs: - self._stubs['get_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetDeliveryVehicle', - request_serializer=delivery_api.GetDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['get_delivery_vehicle'] - - @property - def update_delivery_vehicle(self) -> Callable[ - [delivery_api.UpdateDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - r"""Return a callable for the update delivery vehicle method over gRPC. - - Writes updated ``DeliveryVehicle`` data to Fleet Engine, and - assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update - the name of the ``DeliveryVehicle``. You *can* update - ``remaining_vehicle_journey_segments``, but it must contain all - of the ``VehicleJourneySegment``\ s to be persisted on the - ``DeliveryVehicle``. The ``task_id``\ s are retrieved from - ``remaining_vehicle_journey_segments``, and their corresponding - ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have - not yet been assigned. - - Returns: - Callable[[~.UpdateDeliveryVehicleRequest], - ~.DeliveryVehicle]: - 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_delivery_vehicle' not in self._stubs: - self._stubs['update_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/UpdateDeliveryVehicle', - request_serializer=delivery_api.UpdateDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['update_delivery_vehicle'] - - @property - def batch_create_tasks(self) -> Callable[ - [delivery_api.BatchCreateTasksRequest], - delivery_api.BatchCreateTasksResponse]: - r"""Return a callable for the batch create tasks method over gRPC. - - Creates and returns a batch of new ``Task`` objects. - - Returns: - Callable[[~.BatchCreateTasksRequest], - ~.BatchCreateTasksResponse]: - 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 'batch_create_tasks' not in self._stubs: - self._stubs['batch_create_tasks'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/BatchCreateTasks', - request_serializer=delivery_api.BatchCreateTasksRequest.serialize, - response_deserializer=delivery_api.BatchCreateTasksResponse.deserialize, - ) - return self._stubs['batch_create_tasks'] - - @property - def create_task(self) -> Callable[ - [delivery_api.CreateTaskRequest], - tasks.Task]: - r"""Return a callable for the create task method over gRPC. - - Creates and returns a new ``Task`` object. - - Returns: - Callable[[~.CreateTaskRequest], - ~.Task]: - 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_task' not in self._stubs: - self._stubs['create_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/CreateTask', - request_serializer=delivery_api.CreateTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['create_task'] - - @property - def get_task(self) -> Callable[ - [delivery_api.GetTaskRequest], - tasks.Task]: - r"""Return a callable for the get task method over gRPC. - - Gets information about a ``Task``. - - Returns: - Callable[[~.GetTaskRequest], - ~.Task]: - 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_task' not in self._stubs: - self._stubs['get_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetTask', - request_serializer=delivery_api.GetTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['get_task'] - - @property - def update_task(self) -> Callable[ - [delivery_api.UpdateTaskRequest], - tasks.Task]: - r"""Return a callable for the update task method over gRPC. - - Updates ``Task`` data. - - Returns: - Callable[[~.UpdateTaskRequest], - ~.Task]: - 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_task' not in self._stubs: - self._stubs['update_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/UpdateTask', - request_serializer=delivery_api.UpdateTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['update_task'] - - @property - def list_tasks(self) -> Callable[ - [delivery_api.ListTasksRequest], - delivery_api.ListTasksResponse]: - r"""Return a callable for the list tasks method over gRPC. - - Gets all ``Task``\ s that meet the specified filtering criteria. - - Returns: - Callable[[~.ListTasksRequest], - ~.ListTasksResponse]: - 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_tasks' not in self._stubs: - self._stubs['list_tasks'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/ListTasks', - request_serializer=delivery_api.ListTasksRequest.serialize, - response_deserializer=delivery_api.ListTasksResponse.deserialize, - ) - return self._stubs['list_tasks'] - - @property - def get_task_tracking_info(self) -> Callable[ - [delivery_api.GetTaskTrackingInfoRequest], - task_tracking_info.TaskTrackingInfo]: - r"""Return a callable for the get task tracking info method over gRPC. - - Returns the specified ``TaskTrackingInfo`` instance. - - Returns: - Callable[[~.GetTaskTrackingInfoRequest], - ~.TaskTrackingInfo]: - 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_task_tracking_info' not in self._stubs: - self._stubs['get_task_tracking_info'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetTaskTrackingInfo', - request_serializer=delivery_api.GetTaskTrackingInfoRequest.serialize, - response_deserializer=task_tracking_info.TaskTrackingInfo.deserialize, - ) - return self._stubs['get_task_tracking_info'] - - @property - def list_delivery_vehicles(self) -> Callable[ - [delivery_api.ListDeliveryVehiclesRequest], - delivery_api.ListDeliveryVehiclesResponse]: - r"""Return a callable for the list delivery vehicles method over gRPC. - - Gets all ``DeliveryVehicle``\ s that meet the specified - filtering criteria. - - Returns: - Callable[[~.ListDeliveryVehiclesRequest], - ~.ListDeliveryVehiclesResponse]: - 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_delivery_vehicles' not in self._stubs: - self._stubs['list_delivery_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/ListDeliveryVehicles', - request_serializer=delivery_api.ListDeliveryVehiclesRequest.serialize, - response_deserializer=delivery_api.ListDeliveryVehiclesResponse.deserialize, - ) - return self._stubs['list_delivery_vehicles'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DeliveryServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py deleted file mode 100644 index c8ef910a973a..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,661 +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 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_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks -from .base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DeliveryServiceGrpcTransport - - -class DeliveryServiceGrpcAsyncIOTransport(DeliveryServiceTransport): - """gRPC AsyncIO backend transport for DeliveryService. - - The Last Mile Delivery 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._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_delivery_vehicle(self) -> Callable[ - [delivery_api.CreateDeliveryVehicleRequest], - Awaitable[delivery_vehicles.DeliveryVehicle]]: - r"""Return a callable for the create delivery vehicle method over gRPC. - - Creates and returns a new ``DeliveryVehicle``. - - Returns: - Callable[[~.CreateDeliveryVehicleRequest], - Awaitable[~.DeliveryVehicle]]: - 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_delivery_vehicle' not in self._stubs: - self._stubs['create_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/CreateDeliveryVehicle', - request_serializer=delivery_api.CreateDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['create_delivery_vehicle'] - - @property - def get_delivery_vehicle(self) -> Callable[ - [delivery_api.GetDeliveryVehicleRequest], - Awaitable[delivery_vehicles.DeliveryVehicle]]: - r"""Return a callable for the get delivery vehicle method over gRPC. - - Returns the specified ``DeliveryVehicle`` instance. - - Returns: - Callable[[~.GetDeliveryVehicleRequest], - Awaitable[~.DeliveryVehicle]]: - 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_delivery_vehicle' not in self._stubs: - self._stubs['get_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetDeliveryVehicle', - request_serializer=delivery_api.GetDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['get_delivery_vehicle'] - - @property - def update_delivery_vehicle(self) -> Callable[ - [delivery_api.UpdateDeliveryVehicleRequest], - Awaitable[delivery_vehicles.DeliveryVehicle]]: - r"""Return a callable for the update delivery vehicle method over gRPC. - - Writes updated ``DeliveryVehicle`` data to Fleet Engine, and - assigns ``Tasks`` to the ``DeliveryVehicle``. You cannot update - the name of the ``DeliveryVehicle``. You *can* update - ``remaining_vehicle_journey_segments``, but it must contain all - of the ``VehicleJourneySegment``\ s to be persisted on the - ``DeliveryVehicle``. The ``task_id``\ s are retrieved from - ``remaining_vehicle_journey_segments``, and their corresponding - ``Tasks`` are assigned to the ``DeliveryVehicle`` if they have - not yet been assigned. - - Returns: - Callable[[~.UpdateDeliveryVehicleRequest], - Awaitable[~.DeliveryVehicle]]: - 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_delivery_vehicle' not in self._stubs: - self._stubs['update_delivery_vehicle'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/UpdateDeliveryVehicle', - request_serializer=delivery_api.UpdateDeliveryVehicleRequest.serialize, - response_deserializer=delivery_vehicles.DeliveryVehicle.deserialize, - ) - return self._stubs['update_delivery_vehicle'] - - @property - def batch_create_tasks(self) -> Callable[ - [delivery_api.BatchCreateTasksRequest], - Awaitable[delivery_api.BatchCreateTasksResponse]]: - r"""Return a callable for the batch create tasks method over gRPC. - - Creates and returns a batch of new ``Task`` objects. - - Returns: - Callable[[~.BatchCreateTasksRequest], - Awaitable[~.BatchCreateTasksResponse]]: - 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 'batch_create_tasks' not in self._stubs: - self._stubs['batch_create_tasks'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/BatchCreateTasks', - request_serializer=delivery_api.BatchCreateTasksRequest.serialize, - response_deserializer=delivery_api.BatchCreateTasksResponse.deserialize, - ) - return self._stubs['batch_create_tasks'] - - @property - def create_task(self) -> Callable[ - [delivery_api.CreateTaskRequest], - Awaitable[tasks.Task]]: - r"""Return a callable for the create task method over gRPC. - - Creates and returns a new ``Task`` object. - - Returns: - Callable[[~.CreateTaskRequest], - Awaitable[~.Task]]: - 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_task' not in self._stubs: - self._stubs['create_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/CreateTask', - request_serializer=delivery_api.CreateTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['create_task'] - - @property - def get_task(self) -> Callable[ - [delivery_api.GetTaskRequest], - Awaitable[tasks.Task]]: - r"""Return a callable for the get task method over gRPC. - - Gets information about a ``Task``. - - Returns: - Callable[[~.GetTaskRequest], - Awaitable[~.Task]]: - 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_task' not in self._stubs: - self._stubs['get_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetTask', - request_serializer=delivery_api.GetTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['get_task'] - - @property - def update_task(self) -> Callable[ - [delivery_api.UpdateTaskRequest], - Awaitable[tasks.Task]]: - r"""Return a callable for the update task method over gRPC. - - Updates ``Task`` data. - - Returns: - Callable[[~.UpdateTaskRequest], - Awaitable[~.Task]]: - 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_task' not in self._stubs: - self._stubs['update_task'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/UpdateTask', - request_serializer=delivery_api.UpdateTaskRequest.serialize, - response_deserializer=tasks.Task.deserialize, - ) - return self._stubs['update_task'] - - @property - def list_tasks(self) -> Callable[ - [delivery_api.ListTasksRequest], - Awaitable[delivery_api.ListTasksResponse]]: - r"""Return a callable for the list tasks method over gRPC. - - Gets all ``Task``\ s that meet the specified filtering criteria. - - Returns: - Callable[[~.ListTasksRequest], - Awaitable[~.ListTasksResponse]]: - 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_tasks' not in self._stubs: - self._stubs['list_tasks'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/ListTasks', - request_serializer=delivery_api.ListTasksRequest.serialize, - response_deserializer=delivery_api.ListTasksResponse.deserialize, - ) - return self._stubs['list_tasks'] - - @property - def get_task_tracking_info(self) -> Callable[ - [delivery_api.GetTaskTrackingInfoRequest], - Awaitable[task_tracking_info.TaskTrackingInfo]]: - r"""Return a callable for the get task tracking info method over gRPC. - - Returns the specified ``TaskTrackingInfo`` instance. - - Returns: - Callable[[~.GetTaskTrackingInfoRequest], - Awaitable[~.TaskTrackingInfo]]: - 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_task_tracking_info' not in self._stubs: - self._stubs['get_task_tracking_info'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/GetTaskTrackingInfo', - request_serializer=delivery_api.GetTaskTrackingInfoRequest.serialize, - response_deserializer=task_tracking_info.TaskTrackingInfo.deserialize, - ) - return self._stubs['get_task_tracking_info'] - - @property - def list_delivery_vehicles(self) -> Callable[ - [delivery_api.ListDeliveryVehiclesRequest], - Awaitable[delivery_api.ListDeliveryVehiclesResponse]]: - r"""Return a callable for the list delivery vehicles method over gRPC. - - Gets all ``DeliveryVehicle``\ s that meet the specified - filtering criteria. - - Returns: - Callable[[~.ListDeliveryVehiclesRequest], - Awaitable[~.ListDeliveryVehiclesResponse]]: - 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_delivery_vehicles' not in self._stubs: - self._stubs['list_delivery_vehicles'] = self.grpc_channel.unary_unary( - '/maps.fleetengine.delivery.v1.DeliveryService/ListDeliveryVehicles', - request_serializer=delivery_api.ListDeliveryVehiclesRequest.serialize, - response_deserializer=delivery_api.ListDeliveryVehiclesResponse.deserialize, - ) - return self._stubs['list_delivery_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_delivery_vehicle: gapic_v1.method_async.wrap_method( - self.create_delivery_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_delivery_vehicle: gapic_v1.method_async.wrap_method( - self.get_delivery_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_delivery_vehicle: gapic_v1.method_async.wrap_method( - self.update_delivery_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.batch_create_tasks: gapic_v1.method_async.wrap_method( - self.batch_create_tasks, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_task: gapic_v1.method_async.wrap_method( - self.create_task, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_task: gapic_v1.method_async.wrap_method( - self.get_task, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_task: gapic_v1.method_async.wrap_method( - self.update_task, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_tasks: gapic_v1.method_async.wrap_method( - self.list_tasks, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_task_tracking_info: gapic_v1.method_async.wrap_method( - self.get_task_tracking_info, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_delivery_vehicles: gapic_v1.method_async.wrap_method( - self.list_delivery_vehicles, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - } - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'DeliveryServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py deleted file mode 100644 index 059ce52396ba..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py +++ /dev/null @@ -1,1403 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -from google.maps.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks - -from .base import DeliveryServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DeliveryServiceRestInterceptor: - """Interceptor for DeliveryService. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the DeliveryServiceRestTransport. - - .. code-block:: python - class MyCustomDeliveryServiceInterceptor(DeliveryServiceRestInterceptor): - def pre_batch_create_tasks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_create_tasks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_delivery_vehicle(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_delivery_vehicle(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_task(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_task(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_delivery_vehicle(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_delivery_vehicle(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_task(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_task(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_task_tracking_info(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_task_tracking_info(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_delivery_vehicles(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_delivery_vehicles(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_tasks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_tasks(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_delivery_vehicle(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_delivery_vehicle(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_task(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_task(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DeliveryServiceRestTransport(interceptor=MyCustomDeliveryServiceInterceptor()) - client = DeliveryServiceClient(transport=transport) - - - """ - def pre_batch_create_tasks(self, request: delivery_api.BatchCreateTasksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.BatchCreateTasksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_create_tasks - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_batch_create_tasks(self, response: delivery_api.BatchCreateTasksResponse) -> delivery_api.BatchCreateTasksResponse: - """Post-rpc interceptor for batch_create_tasks - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - def pre_create_delivery_vehicle(self, request: delivery_api.CreateDeliveryVehicleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.CreateDeliveryVehicleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_delivery_vehicle - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_create_delivery_vehicle(self, response: delivery_vehicles.DeliveryVehicle) -> delivery_vehicles.DeliveryVehicle: - """Post-rpc interceptor for create_delivery_vehicle - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - def pre_create_task(self, request: delivery_api.CreateTaskRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.CreateTaskRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_task - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_create_task(self, response: tasks.Task) -> tasks.Task: - """Post-rpc interceptor for create_task - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - def pre_get_delivery_vehicle(self, request: delivery_api.GetDeliveryVehicleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.GetDeliveryVehicleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_delivery_vehicle - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_get_delivery_vehicle(self, response: delivery_vehicles.DeliveryVehicle) -> delivery_vehicles.DeliveryVehicle: - """Post-rpc interceptor for get_delivery_vehicle - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - def pre_get_task(self, request: delivery_api.GetTaskRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.GetTaskRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_task - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_get_task(self, response: tasks.Task) -> tasks.Task: - """Post-rpc interceptor for get_task - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - def pre_get_task_tracking_info(self, request: delivery_api.GetTaskTrackingInfoRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.GetTaskTrackingInfoRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_task_tracking_info - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_get_task_tracking_info(self, response: task_tracking_info.TaskTrackingInfo) -> task_tracking_info.TaskTrackingInfo: - """Post-rpc interceptor for get_task_tracking_info - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - def pre_list_delivery_vehicles(self, request: delivery_api.ListDeliveryVehiclesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.ListDeliveryVehiclesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_delivery_vehicles - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_list_delivery_vehicles(self, response: delivery_api.ListDeliveryVehiclesResponse) -> delivery_api.ListDeliveryVehiclesResponse: - """Post-rpc interceptor for list_delivery_vehicles - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - def pre_list_tasks(self, request: delivery_api.ListTasksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.ListTasksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_tasks - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_list_tasks(self, response: delivery_api.ListTasksResponse) -> delivery_api.ListTasksResponse: - """Post-rpc interceptor for list_tasks - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - def pre_update_delivery_vehicle(self, request: delivery_api.UpdateDeliveryVehicleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.UpdateDeliveryVehicleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_delivery_vehicle - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_update_delivery_vehicle(self, response: delivery_vehicles.DeliveryVehicle) -> delivery_vehicles.DeliveryVehicle: - """Post-rpc interceptor for update_delivery_vehicle - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - def pre_update_task(self, request: delivery_api.UpdateTaskRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[delivery_api.UpdateTaskRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_task - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_update_task(self, response: tasks.Task) -> tasks.Task: - """Post-rpc interceptor for update_task - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DeliveryServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DeliveryServiceRestInterceptor - - -class DeliveryServiceRestTransport(DeliveryServiceTransport): - """REST backend transport for DeliveryService. - - The Last Mile Delivery 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 JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'fleetengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[DeliveryServiceRestInterceptor] = None, - 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. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DeliveryServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _BatchCreateTasks(DeliveryServiceRestStub): - def __hash__(self): - return hash("BatchCreateTasks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: delivery_api.BatchCreateTasksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_api.BatchCreateTasksResponse: - r"""Call the batch create tasks method over HTTP. - - Args: - request (~.delivery_api.BatchCreateTasksRequest): - The request object. The ``BatchCreateTask`` 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: - ~.delivery_api.BatchCreateTasksResponse: - The ``BatchCreateTask`` response message. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=providers/*}/tasks:batchCreate', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_batch_create_tasks(request, metadata) - pb_request = delivery_api.BatchCreateTasksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = delivery_api.BatchCreateTasksResponse() - pb_resp = delivery_api.BatchCreateTasksResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_create_tasks(resp) - return resp - - class _CreateDeliveryVehicle(DeliveryServiceRestStub): - def __hash__(self): - return hash("CreateDeliveryVehicle") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "deliveryVehicleId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: delivery_api.CreateDeliveryVehicleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Call the create delivery vehicle method over HTTP. - - Args: - request (~.delivery_api.CreateDeliveryVehicleRequest): - The request object. The ``CreateDeliveryVehicle`` 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: - ~.delivery_vehicles.DeliveryVehicle: - The ``DeliveryVehicle`` message. A delivery vehicle - transports shipments from a depot to a delivery - location, and from a pickup location to the depot. In - some cases, delivery vehicles also transport shipments - directly from the pickup location to the delivery - location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``DeliveryVehicle.current_route_segment`` field in the - gRPC API and the ``DeliveryVehicle.currentRouteSegment`` - field in the REST API refer to the same field. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=providers/*}/deliveryVehicles', - 'body': 'delivery_vehicle', - }, - ] - request, metadata = self._interceptor.pre_create_delivery_vehicle(request, metadata) - pb_request = delivery_api.CreateDeliveryVehicleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = delivery_vehicles.DeliveryVehicle() - pb_resp = delivery_vehicles.DeliveryVehicle.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_delivery_vehicle(resp) - return resp - - class _CreateTask(DeliveryServiceRestStub): - def __hash__(self): - return hash("CreateTask") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "taskId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: delivery_api.CreateTaskRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tasks.Task: - r"""Call the create task method over HTTP. - - Args: - request (~.delivery_api.CreateTaskRequest): - The request object. The ``CreateTask`` 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: - ~.tasks.Task: - A Task in the Delivery API represents a single action to - track. In general, there is a distinction between - shipment-related Tasks and break Tasks. A shipment can - have multiple Tasks associated with it. For example, - there could be one Task for the pickup, and one for the - drop-off or transfer. Also, different Tasks for a given - shipment can be handled by different vehicles. For - example, one vehicle could handle the pickup, driving - the shipment to the hub, while another vehicle drives - the same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``Task.journey_sharing_info`` field in the gRPC API and - the ``Task.journeySharingInfo`` field in the REST API - refer to the same field. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=providers/*}/tasks', - 'body': 'task', - }, - ] - request, metadata = self._interceptor.pre_create_task(request, metadata) - pb_request = delivery_api.CreateTaskRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tasks.Task() - pb_resp = tasks.Task.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_task(resp) - return resp - - class _GetDeliveryVehicle(DeliveryServiceRestStub): - def __hash__(self): - return hash("GetDeliveryVehicle") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: delivery_api.GetDeliveryVehicleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Call the get delivery vehicle method over HTTP. - - Args: - request (~.delivery_api.GetDeliveryVehicleRequest): - The request object. The ``GetDeliveryVehicle`` 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: - ~.delivery_vehicles.DeliveryVehicle: - The ``DeliveryVehicle`` message. A delivery vehicle - transports shipments from a depot to a delivery - location, and from a pickup location to the depot. In - some cases, delivery vehicles also transport shipments - directly from the pickup location to the delivery - location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``DeliveryVehicle.current_route_segment`` field in the - gRPC API and the ``DeliveryVehicle.currentRouteSegment`` - field in the REST API refer to the same field. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=providers/*/deliveryVehicles/*}', - }, - ] - request, metadata = self._interceptor.pre_get_delivery_vehicle(request, metadata) - pb_request = delivery_api.GetDeliveryVehicleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = delivery_vehicles.DeliveryVehicle() - pb_resp = delivery_vehicles.DeliveryVehicle.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_delivery_vehicle(resp) - return resp - - class _GetTask(DeliveryServiceRestStub): - def __hash__(self): - return hash("GetTask") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: delivery_api.GetTaskRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tasks.Task: - r"""Call the get task method over HTTP. - - Args: - request (~.delivery_api.GetTaskRequest): - The request object. The ``GetTask`` 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: - ~.tasks.Task: - A Task in the Delivery API represents a single action to - track. In general, there is a distinction between - shipment-related Tasks and break Tasks. A shipment can - have multiple Tasks associated with it. For example, - there could be one Task for the pickup, and one for the - drop-off or transfer. Also, different Tasks for a given - shipment can be handled by different vehicles. For - example, one vehicle could handle the pickup, driving - the shipment to the hub, while another vehicle drives - the same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``Task.journey_sharing_info`` field in the gRPC API and - the ``Task.journeySharingInfo`` field in the REST API - refer to the same field. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=providers/*/tasks/*}', - }, - ] - request, metadata = self._interceptor.pre_get_task(request, metadata) - pb_request = delivery_api.GetTaskRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tasks.Task() - pb_resp = tasks.Task.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_task(resp) - return resp - - class _GetTaskTrackingInfo(DeliveryServiceRestStub): - def __hash__(self): - return hash("GetTaskTrackingInfo") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: delivery_api.GetTaskTrackingInfoRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> task_tracking_info.TaskTrackingInfo: - r"""Call the get task tracking info method over HTTP. - - Args: - request (~.delivery_api.GetTaskTrackingInfoRequest): - The request object. The ``GetTaskTrackingInfoRequest`` 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: - ~.task_tracking_info.TaskTrackingInfo: - The ``TaskTrackingInfo`` message. The message contains - task tracking information which will be used for - display. If a tracking ID is associated with multiple - Tasks, Fleet Engine uses a heuristic to decide which - Task's TaskTrackingInfo to select. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=providers/*/taskTrackingInfo/*}', - }, - ] - request, metadata = self._interceptor.pre_get_task_tracking_info(request, metadata) - pb_request = delivery_api.GetTaskTrackingInfoRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = task_tracking_info.TaskTrackingInfo() - pb_resp = task_tracking_info.TaskTrackingInfo.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_task_tracking_info(resp) - return resp - - class _ListDeliveryVehicles(DeliveryServiceRestStub): - def __hash__(self): - return hash("ListDeliveryVehicles") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: delivery_api.ListDeliveryVehiclesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_api.ListDeliveryVehiclesResponse: - r"""Call the list delivery vehicles method over HTTP. - - Args: - request (~.delivery_api.ListDeliveryVehiclesRequest): - The request object. The ``ListDeliveryVehicles`` 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: - ~.delivery_api.ListDeliveryVehiclesResponse: - The ``ListDeliveryVehicles`` response message. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=providers/*}/deliveryVehicles', - }, - ] - request, metadata = self._interceptor.pre_list_delivery_vehicles(request, metadata) - pb_request = delivery_api.ListDeliveryVehiclesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = delivery_api.ListDeliveryVehiclesResponse() - pb_resp = delivery_api.ListDeliveryVehiclesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_delivery_vehicles(resp) - return resp - - class _ListTasks(DeliveryServiceRestStub): - def __hash__(self): - return hash("ListTasks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: delivery_api.ListTasksRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_api.ListTasksResponse: - r"""Call the list tasks method over HTTP. - - Args: - request (~.delivery_api.ListTasksRequest): - The request object. The ``ListTasks`` 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: - ~.delivery_api.ListTasksResponse: - The ``ListTasks`` response that contains the set of - Tasks that meet the filter criteria in the - ``ListTasksRequest``. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=providers/*}/tasks', - }, - ] - request, metadata = self._interceptor.pre_list_tasks(request, metadata) - pb_request = delivery_api.ListTasksRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = delivery_api.ListTasksResponse() - pb_resp = delivery_api.ListTasksResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_tasks(resp) - return resp - - class _UpdateDeliveryVehicle(DeliveryServiceRestStub): - def __hash__(self): - return hash("UpdateDeliveryVehicle") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: delivery_api.UpdateDeliveryVehicleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> delivery_vehicles.DeliveryVehicle: - r"""Call the update delivery vehicle method over HTTP. - - Args: - request (~.delivery_api.UpdateDeliveryVehicleRequest): - The request object. The ``UpdateDeliveryVehicle`` 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: - ~.delivery_vehicles.DeliveryVehicle: - The ``DeliveryVehicle`` message. A delivery vehicle - transports shipments from a depot to a delivery - location, and from a pickup location to the depot. In - some cases, delivery vehicles also transport shipments - directly from the pickup location to the delivery - location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``DeliveryVehicle.current_route_segment`` field in the - gRPC API and the ``DeliveryVehicle.currentRouteSegment`` - field in the REST API refer to the same field. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{delivery_vehicle.name=providers/*/deliveryVehicles/*}', - 'body': 'delivery_vehicle', - }, - ] - request, metadata = self._interceptor.pre_update_delivery_vehicle(request, metadata) - pb_request = delivery_api.UpdateDeliveryVehicleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = delivery_vehicles.DeliveryVehicle() - pb_resp = delivery_vehicles.DeliveryVehicle.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_delivery_vehicle(resp) - return resp - - class _UpdateTask(DeliveryServiceRestStub): - def __hash__(self): - return hash("UpdateTask") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: delivery_api.UpdateTaskRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> tasks.Task: - r"""Call the update task method over HTTP. - - Args: - request (~.delivery_api.UpdateTaskRequest): - The request object. The ``UpdateTask`` 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: - ~.tasks.Task: - A Task in the Delivery API represents a single action to - track. In general, there is a distinction between - shipment-related Tasks and break Tasks. A shipment can - have multiple Tasks associated with it. For example, - there could be one Task for the pickup, and one for the - drop-off or transfer. Also, different Tasks for a given - shipment can be handled by different vehicles. For - example, one vehicle could handle the pickup, driving - the shipment to the hub, while another vehicle drives - the same shipment from the hub to the drop-off location. - - Note: gRPC and REST APIs use different field naming - conventions. For example, the - ``Task.journey_sharing_info`` field in the gRPC API and - the ``Task.journeySharingInfo`` field in the REST API - refer to the same field. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{task.name=providers/*/tasks/*}', - 'body': 'task', - }, - ] - request, metadata = self._interceptor.pre_update_task(request, metadata) - pb_request = delivery_api.UpdateTaskRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = tasks.Task() - pb_resp = tasks.Task.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_task(resp) - return resp - - @property - def batch_create_tasks(self) -> Callable[ - [delivery_api.BatchCreateTasksRequest], - delivery_api.BatchCreateTasksResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._BatchCreateTasks(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_delivery_vehicle(self) -> Callable[ - [delivery_api.CreateDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateDeliveryVehicle(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_task(self) -> Callable[ - [delivery_api.CreateTaskRequest], - tasks.Task]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateTask(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_delivery_vehicle(self) -> Callable[ - [delivery_api.GetDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDeliveryVehicle(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_task(self) -> Callable[ - [delivery_api.GetTaskRequest], - tasks.Task]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetTask(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_task_tracking_info(self) -> Callable[ - [delivery_api.GetTaskTrackingInfoRequest], - task_tracking_info.TaskTrackingInfo]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetTaskTrackingInfo(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_delivery_vehicles(self) -> Callable[ - [delivery_api.ListDeliveryVehiclesRequest], - delivery_api.ListDeliveryVehiclesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDeliveryVehicles(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_tasks(self) -> Callable[ - [delivery_api.ListTasksRequest], - delivery_api.ListTasksResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListTasks(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_delivery_vehicle(self) -> Callable[ - [delivery_api.UpdateDeliveryVehicleRequest], - delivery_vehicles.DeliveryVehicle]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateDeliveryVehicle(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_task(self) -> Callable[ - [delivery_api.UpdateTaskRequest], - tasks.Task]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateTask(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DeliveryServiceRestTransport', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__init__.py deleted file mode 100644 index e2051b3b85ad..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/__init__.py +++ /dev/null @@ -1,84 +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 .common import ( - DeliveryVehicleAttribute, - DeliveryVehicleLocation, - TaskAttribute, - TimeWindow, - DeliveryVehicleLocationSensor, - DeliveryVehicleNavigationStatus, -) -from .delivery_api import ( - BatchCreateTasksRequest, - BatchCreateTasksResponse, - CreateDeliveryVehicleRequest, - CreateTaskRequest, - GetDeliveryVehicleRequest, - GetTaskRequest, - GetTaskTrackingInfoRequest, - ListDeliveryVehiclesRequest, - ListDeliveryVehiclesResponse, - ListTasksRequest, - ListTasksResponse, - UpdateDeliveryVehicleRequest, - UpdateTaskRequest, -) -from .delivery_vehicles import ( - DeliveryVehicle, - LocationInfo, - VehicleJourneySegment, - VehicleStop, -) -from .header import ( - DeliveryRequestHeader, -) -from .task_tracking_info import ( - TaskTrackingInfo, -) -from .tasks import ( - Task, - TaskTrackingViewConfig, -) - -__all__ = ( - 'DeliveryVehicleAttribute', - 'DeliveryVehicleLocation', - 'TaskAttribute', - 'TimeWindow', - 'DeliveryVehicleLocationSensor', - 'DeliveryVehicleNavigationStatus', - 'BatchCreateTasksRequest', - 'BatchCreateTasksResponse', - 'CreateDeliveryVehicleRequest', - 'CreateTaskRequest', - 'GetDeliveryVehicleRequest', - 'GetTaskRequest', - 'GetTaskTrackingInfoRequest', - 'ListDeliveryVehiclesRequest', - 'ListDeliveryVehiclesResponse', - 'ListTasksRequest', - 'ListTasksResponse', - 'UpdateDeliveryVehicleRequest', - 'UpdateTaskRequest', - 'DeliveryVehicle', - 'LocationInfo', - 'VehicleJourneySegment', - 'VehicleStop', - 'DeliveryRequestHeader', - 'TaskTrackingInfo', - 'Task', - 'TaskTrackingViewConfig', -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.py deleted file mode 100644 index f0fa11ac4ff5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/common.py +++ /dev/null @@ -1,471 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import 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.delivery.v1', - manifest={ - 'DeliveryVehicleLocationSensor', - 'DeliveryVehicleNavigationStatus', - 'DeliveryVehicleAttribute', - 'DeliveryVehicleLocation', - 'TimeWindow', - 'TaskAttribute', - }, -) - - -class DeliveryVehicleLocationSensor(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 - DeliveryVehicle'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 DeliveryVehicleNavigationStatus(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 DeliveryVehicleAttribute(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. - 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`_ ``delivery_vehicle_attribute_value``. - bool_value (bool): - Boolean typed attribute value. - - This field is a member of `oneof`_ ``delivery_vehicle_attribute_value``. - number_value (float): - Double typed attribute value. - - This field is a member of `oneof`_ ``delivery_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='delivery_vehicle_attribute_value', - ) - bool_value: bool = proto.Field( - proto.BOOL, - number=4, - oneof='delivery_vehicle_attribute_value', - ) - number_value: float = proto.Field( - proto.DOUBLE, - number=5, - oneof='delivery_vehicle_attribute_value', - ) - - -class DeliveryVehicleLocation(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_delivery_v1.types.DeliveryVehicleLocationSensor): - 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_delivery_v1.types.DeliveryVehicleLocationSensor): - 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_delivery_v1.types.DeliveryVehicleLocationSensor): - 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: 'DeliveryVehicleLocationSensor' = proto.Field( - proto.ENUM, - number=11, - enum='DeliveryVehicleLocationSensor', - ) - 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: 'DeliveryVehicleLocationSensor' = proto.Field( - proto.ENUM, - number=28, - enum='DeliveryVehicleLocationSensor', - ) - 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: 'DeliveryVehicleLocationSensor' = proto.Field( - proto.ENUM, - number=20, - enum='DeliveryVehicleLocationSensor', - ) - 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, - ) - - -class TimeWindow(proto.Message): - r"""A time range. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The start time of the time window - (inclusive). - end_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The end time of the time window - (inclusive). - """ - - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class TaskAttribute(proto.Message): - r"""Describes a task 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 (:). - string_value (str): - String typed attribute value. - - This field is a member of `oneof`_ ``task_attribute_value``. - bool_value (bool): - Boolean typed attribute value. - - This field is a member of `oneof`_ ``task_attribute_value``. - number_value (float): - Double typed attribute value. - - This field is a member of `oneof`_ ``task_attribute_value``. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - string_value: str = proto.Field( - proto.STRING, - number=2, - oneof='task_attribute_value', - ) - bool_value: bool = proto.Field( - proto.BOOL, - number=3, - oneof='task_attribute_value', - ) - number_value: float = proto.Field( - proto.DOUBLE, - number=4, - oneof='task_attribute_value', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py deleted file mode 100644 index e32df11b607b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_api.py +++ /dev/null @@ -1,603 +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_delivery_v1.types import delivery_vehicles as mfd_delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import header as mfd_header -from google.maps.fleetengine_delivery_v1.types import tasks as mfd_tasks -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.delivery.v1', - manifest={ - 'CreateDeliveryVehicleRequest', - 'GetDeliveryVehicleRequest', - 'ListDeliveryVehiclesRequest', - 'ListDeliveryVehiclesResponse', - 'UpdateDeliveryVehicleRequest', - 'BatchCreateTasksRequest', - 'BatchCreateTasksResponse', - 'CreateTaskRequest', - 'GetTaskRequest', - 'UpdateTaskRequest', - 'ListTasksRequest', - 'ListTasksResponse', - 'GetTaskTrackingInfoRequest', - }, -) - - -class CreateDeliveryVehicleRequest(proto.Message): - r"""The ``CreateDeliveryVehicle`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. - delivery_vehicle_id (str): - Required. The Delivery Vehicle ID must be unique and 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 '#'. - delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): - Required. The ``DeliveryVehicle`` entity to create. When - creating a new delivery vehicle, you may set the following - optional fields: - - - type - - last_location - - attributes - - Note: The DeliveryVehicle's ``name`` field is ignored. All - other DeliveryVehicle fields must not be set; otherwise, an - error is returned. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - delivery_vehicle_id: str = proto.Field( - proto.STRING, - number=4, - ) - delivery_vehicle: mfd_delivery_vehicles.DeliveryVehicle = proto.Field( - proto.MESSAGE, - number=5, - message=mfd_delivery_vehicles.DeliveryVehicle, - ) - - -class GetDeliveryVehicleRequest(proto.Message): - r"""The ``GetDeliveryVehicle`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - name (str): - Required. Must be in the format - ``providers/{provider}/deliveryVehicles/{delivery_vehicle}``. - The ``provider`` must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListDeliveryVehiclesRequest(proto.Message): - r"""The ``ListDeliveryVehicles`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The ``provider`` must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. - page_size (int): - Optional. The maximum number of vehicles to - return. The service may return fewer than this - number. If you don't specify this number, then - the server determines the number of results to - return. - page_token (str): - Optional. A page token, received from a previous - ``ListDeliveryVehicles`` call. You must provide this in - order to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListDeliveryVehicles`` must match the call that provided - the page token. - filter (str): - Optional. A filter query to apply when listing delivery - vehicles. See http://aip.dev/160 for examples of the filter - syntax. If you don't specify a value, or if you specify an - empty string for the filter, then all delivery vehicles are - returned. - - Note that the only queries supported for - ``ListDeliveryVehicles`` are on vehicle attributes (for - example, ``attributes. = `` or - ``attributes. = AND attributes. = ``). - 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"``). - - The maximum number of restrictions allowed in a filter query - is 50. A restriction is a part of the query of the form - ``attribute. ``, for example - ``attributes.foo = bar`` is 1 restriction. - 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: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - filter: str = proto.Field( - proto.STRING, - number=6, - ) - viewport: ggt_viewport.Viewport = proto.Field( - proto.MESSAGE, - number=7, - message=ggt_viewport.Viewport, - ) - - -class ListDeliveryVehiclesResponse(proto.Message): - r"""The ``ListDeliveryVehicles`` response message. - - Attributes: - delivery_vehicles (MutableSequence[google.maps.fleetengine_delivery_v1.types.DeliveryVehicle]): - The set of delivery vehicles that meet the - requested filtering criteria. When no filter is - specified, the request returns all delivery - vehicles. A successful response can also be - empty. An empty response indicates that no - delivery vehicles were found meeting the - requested filter criteria. - next_page_token (str): - You can pass this token in the - ``ListDeliveryVehiclesRequest`` to continue to list results. - When all of the results are returned, this field won't be in - the response, or it will be an empty string. - total_size (int): - The total number of delivery vehicles that - match the request criteria, across all pages. - """ - - @property - def raw_page(self): - return self - - delivery_vehicles: MutableSequence[mfd_delivery_vehicles.DeliveryVehicle] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=mfd_delivery_vehicles.DeliveryVehicle, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT64, - number=3, - ) - - -class UpdateDeliveryVehicleRequest(proto.Message): - r"""The ``UpdateDeliveryVehicle`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - delivery_vehicle (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle): - Required. The ``DeliveryVehicle`` entity update to apply. - Note: You cannot update the name of the ``DeliveryVehicle``. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. A field mask that indicates which - ``DeliveryVehicle`` fields to update. Note that the - update_mask must contain at least one field. - - This is a comma-separated list of fully qualified names of - fields. Example: ``"remaining_vehicle_journey_segments"``. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - delivery_vehicle: mfd_delivery_vehicles.DeliveryVehicle = proto.Field( - proto.MESSAGE, - number=3, - message=mfd_delivery_vehicles.DeliveryVehicle, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class BatchCreateTasksRequest(proto.Message): - r"""The ``BatchCreateTask`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request header. Note: If - you set this field, then the header field in the - ``CreateTaskRequest`` messages must either be empty, or it - must match this field. - parent (str): - Required. The parent resource shared by all tasks. This - value must be in the format ``providers/{provider}``. The - ``provider`` must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. The parent field in the - ``CreateTaskRequest`` messages must either be empty, or it - must match this field. - requests (MutableSequence[google.maps.fleetengine_delivery_v1.types.CreateTaskRequest]): - Required. The request message that specifies - the resources to create. Note: You can create a - maximum of 500 tasks in a batch. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - requests: MutableSequence['CreateTaskRequest'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='CreateTaskRequest', - ) - - -class BatchCreateTasksResponse(proto.Message): - r"""The ``BatchCreateTask`` response message. - - Attributes: - tasks (MutableSequence[google.maps.fleetengine_delivery_v1.types.Task]): - The created Tasks. - """ - - tasks: MutableSequence[mfd_tasks.Task] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=mfd_tasks.Task, - ) - - -class CreateTaskRequest(proto.Message): - r"""The ``CreateTask`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The ``provider`` must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. - task_id (str): - Required. The Task ID must be unique, but it should be not a - shipment tracking ID. To store a shipment tracking ID, use - the ``tracking_id`` field. Note that multiple tasks can have - the same ``tracking_id``. Task IDs are 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 '#'. - task (google.maps.fleetengine_delivery_v1.types.Task): - Required. The Task entity to create. When creating a Task, - the following fields are required: - - - ``type`` - - ``state`` (must be set to ``OPEN``) - - ``tracking_id`` (must not be set for ``UNAVAILABLE`` or - ``SCHEDULED_STOP`` tasks, but required for all other task - types) - - ``planned_location`` (optional for ``UNAVAILABLE`` tasks) - - ``task_duration`` - - Note: The Task's ``name`` field is ignored. All other Task - fields must not be set; otherwise, an error is returned. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - task_id: str = proto.Field( - proto.STRING, - number=5, - ) - task: mfd_tasks.Task = proto.Field( - proto.MESSAGE, - number=4, - message=mfd_tasks.Task, - ) - - -class GetTaskRequest(proto.Message): - r"""The ``GetTask`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - name (str): - Required. Must be in the format - ``providers/{provider}/tasks/{task}``. The ``provider`` must - be the Google Cloud Project ID. For example, - ``sample-cloud-project``. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateTaskRequest(proto.Message): - r"""The ``UpdateTask`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - task (google.maps.fleetengine_delivery_v1.types.Task): - Required. The Task associated with the update. The following - fields are maintained by Fleet Engine. Do not update them - using ``Task.update``. - - - ``last_location``. - - ``last_location_snappable``. - - ``name``. - - ``remaining_vehicle_journey_segments``. - - ``task_outcome_location_source``. - - Note: You cannot change the value of ``task_outcome`` once - you set it. - - If the Task has been assigned to a delivery vehicle, then - don't set the Task state to CLOSED using ``Task.update``. - Instead, remove the ``VehicleStop`` that contains the Task - from the delivery vehicle, which automatically sets the Task - state to CLOSED. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The field mask that indicates which Task fields to - update. Note: The ``update_mask`` must contain at least one - field. - - This is a comma-separated list of fully qualified names of - fields. Example: - ``"task_outcome,task_outcome_time,task_outcome_location"``. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - task: mfd_tasks.Task = proto.Field( - proto.MESSAGE, - number=3, - message=mfd_tasks.Task, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - - -class ListTasksRequest(proto.Message): - r"""The ``ListTasks`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The ``provider`` must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. - page_size (int): - Optional. The maximum number of Tasks to - return. The service may return fewer than this - value. If you don't specify this value, then the - server determines the number of results to - return. - page_token (str): - Optional. A page token received from a previous - ``ListTasks`` call. You can provide this to retrieve the - subsequent page. - - When paginating, all other parameters provided to - ``ListTasks`` must match the call that provided the page - token. - filter (str): - Optional. A filter query to apply when listing Tasks. See - http://aip.dev/160 for examples of filter syntax. If you - don't specify a value, or if you filter on an empty string, - then all Tasks are returned. For information about the Task - properties that you can filter on, see `List - tasks `__. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - filter: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ListTasksResponse(proto.Message): - r"""The ``ListTasks`` response that contains the set of Tasks that meet - the filter criteria in the ``ListTasksRequest``. - - Attributes: - tasks (MutableSequence[google.maps.fleetengine_delivery_v1.types.Task]): - The set of Tasks that meet the requested - filtering criteria. When no filter is specified, - the request returns all tasks. A successful - response can also be empty. An empty response - indicates that no Tasks were found meeting the - requested filter criteria. - next_page_token (str): - Pass this token in the ``ListTasksRequest`` to continue to - list results. If all results have been returned, then this - field is either an empty string, or it doesn't appear in the - response. - total_size (int): - The total number of Tasks that match the - request criteria, across all pages. - """ - - @property - def raw_page(self): - return self - - tasks: MutableSequence[mfd_tasks.Task] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=mfd_tasks.Task, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT64, - number=3, - ) - - -class GetTaskTrackingInfoRequest(proto.Message): - r"""The ``GetTaskTrackingInfoRequest`` request message. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - name (str): - Required. Must be in the format - ``providers/{provider}/taskTrackingInfo/{tracking_id}``. The - ``provider`` must be the Google Cloud Project ID, and the - ``tracking_id`` must be the tracking ID associated with the - task. An example name can be - ``providers/sample-cloud-project/taskTrackingInfo/sample-tracking-id``. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py deleted file mode 100644 index 2ded1f83bf92..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/delivery_vehicles.py +++ /dev/null @@ -1,414 +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_delivery_v1.types import common -from google.protobuf import duration_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.delivery.v1', - manifest={ - 'DeliveryVehicle', - 'LocationInfo', - 'VehicleJourneySegment', - 'VehicleStop', - }, -) - - -class DeliveryVehicle(proto.Message): - r"""The ``DeliveryVehicle`` message. A delivery vehicle transports - shipments from a depot to a delivery location, and from a pickup - location to the depot. In some cases, delivery vehicles also - transport shipments directly from the pickup location to the - delivery location. - - Note: gRPC and REST APIs use different field naming conventions. For - example, the ``DeliveryVehicle.current_route_segment`` field in the - gRPC API and the ``DeliveryVehicle.currentRouteSegment`` field in - the REST API refer to the same field. - - Attributes: - name (str): - The unique name of this Delivery Vehicle. The format is - ``providers/{provider}/deliveryVehicles/{vehicle}``. - last_location (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocation): - The last reported location of the Delivery - Vehicle. - navigation_status (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleNavigationStatus): - The Delivery Vehicle's navigation status. - current_route_segment (bytes): - The encoded polyline specifying the route that the - navigation recommends taking to the next waypoint. Your - driver app updates this when a stop is reached or passed, - and when the navigation reroutes. These ``LatLng``\ s are - returned in - ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0].path`` - (gRPC) or - ``Task.journeySharingInfo.remainingVehicleJourneySegments[0].path`` - (REST) for all active Tasks assigned to the Vehicle. - - There are a few cases where this field might not be used to - populate - ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0].path`` - (gRPC) or - ``Task.journeySharingInfo.remainingVehicleJourneySegments[0].path`` - (REST): - - - The endpoint of the ``current_route_segment`` does not - match - ``DeliveryVehicle.remaining_vehicle_journey_segments[0].stop`` - (gRPC) or - ``DeliveryVehicle.remainingVehicleJourneySegments[0].stop`` - (REST). - - - The driver app has not updated its location recently, so - the last updated value for this field might be stale. - - - The driver app has recently updated its location, but the - ``current_route_segment`` is stale, and points to a - previous vehicle stop. - - In these cases, Fleet Engine populates this field with a - route from the most recently passed VehicleStop to the - upcoming VehicleStop to ensure that the consumer of this - field has the best available information on the current path - of the Delivery Vehicle. - current_route_segment_end_point (google.type.latlng_pb2.LatLng): - The location where the ``current_route_segment`` ends. This - is not currently populated by the driver app, but you can - supply it on ``UpdateDeliveryVehicle`` calls. It is either - the ``LatLng`` from the upcoming vehicle stop, or the last - ``LatLng`` of the ``current_route_segment``. Fleet Engine - will then do its best to interpolate to an actual - ``VehicleStop``. - - This field is ignored in ``UpdateDeliveryVehicle`` calls if - the ``current_route_segment`` field is empty. - remaining_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The remaining driving distance for the - ``current_route_segment``. The Driver app typically provides - this field, but there are some circumstances in which Fleet - Engine will override the value sent by the app. For more - information, see - [DeliveryVehicle.current_route_segment][maps.fleetengine.delivery.v1.DeliveryVehicle.current_route_segment]. - This field is returned in - ``Task.remaining_vehicle_journey_segments[0].driving_distance_meters`` - (gRPC) or - ``Task.remainingVehicleJourneySegments[0].drivingDistanceMeters`` - (REST) for all active ``Task``\ s assigned to the Delivery - Vehicle. - - Fleet Engine ignores this field in - ``UpdateDeliveryVehicleRequest`` if the - ``current_route_segment`` field is empty. - remaining_duration (google.protobuf.duration_pb2.Duration): - The remaining driving time for the - ``current_route_segment``. The Driver app typically provides - this field, but there are some circumstances in which Fleet - Engine will override the value sent by the app. For more - information, see - [DeliveryVehicle.current_route_segment][maps.fleetengine.delivery.v1.DeliveryVehicle.current_route_segment]. - This field is returned in - ``Task.remaining_vehicle_journey_segments[0].driving_duration`` - (gRPC) or - ``Task.remainingVehicleJourneySegments[0].drivingDuration`` - (REST) for all active tasks assigned to the Delivery - Vehicle. - - Fleet Engine ignores this field in - ``UpdateDeliveryVehicleRequest`` if the - ``current_route_segment`` field is empty. - remaining_vehicle_journey_segments (MutableSequence[google.maps.fleetengine_delivery_v1.types.VehicleJourneySegment]): - The journey segments assigned to this Delivery Vehicle, - starting from the Vehicle's most recently reported location. - This field won't be populated in the response of - ``ListDeliveryVehicles``. - attributes (MutableSequence[google.maps.fleetengine_delivery_v1.types.DeliveryVehicleAttribute]): - A list of custom Delivery Vehicle attributes. - A Delivery Vehicle can have at most 100 - attributes, and each attribute must have a - unique key. - type_ (google.maps.fleetengine_delivery_v1.types.DeliveryVehicle.DeliveryVehicleType): - The type of this delivery vehicle. If unset, this will - default to ``AUTO``. - """ - class DeliveryVehicleType(proto.Enum): - r"""The type of delivery vehicle. - - Values: - DELIVERY_VEHICLE_TYPE_UNSPECIFIED (0): - The value is unused. - AUTO (1): - An automobile. - TWO_WHEELER (2): - A motorcycle, moped, or other two-wheeled - vehicle - BICYCLE (3): - Human-powered transport. - PEDESTRIAN (4): - A human transporter, typically walking or - running, traveling along pedestrian pathways. - """ - DELIVERY_VEHICLE_TYPE_UNSPECIFIED = 0 - AUTO = 1 - TWO_WHEELER = 2 - BICYCLE = 3 - PEDESTRIAN = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - last_location: common.DeliveryVehicleLocation = proto.Field( - proto.MESSAGE, - number=2, - message=common.DeliveryVehicleLocation, - ) - navigation_status: common.DeliveryVehicleNavigationStatus = proto.Field( - proto.ENUM, - number=3, - enum=common.DeliveryVehicleNavigationStatus, - ) - current_route_segment: bytes = proto.Field( - proto.BYTES, - number=4, - ) - current_route_segment_end_point: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=5, - message=latlng_pb2.LatLng, - ) - remaining_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.Int32Value, - ) - remaining_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - remaining_vehicle_journey_segments: MutableSequence['VehicleJourneySegment'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='VehicleJourneySegment', - ) - attributes: MutableSequence[common.DeliveryVehicleAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=common.DeliveryVehicleAttribute, - ) - type_: DeliveryVehicleType = proto.Field( - proto.ENUM, - number=10, - enum=DeliveryVehicleType, - ) - - -class LocationInfo(proto.Message): - r"""A location with any additional identifiers. - - Attributes: - point (google.type.latlng_pb2.LatLng): - The location's coordinates. - """ - - point: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - - -class VehicleJourneySegment(proto.Message): - r"""Represents a Vehicle’s travel segment - from its previous - stop to the current stop. If it is the first active stop, then - it is from the Vehicle’s current location to this stop. - - Attributes: - stop (google.maps.fleetengine_delivery_v1.types.VehicleStop): - Specifies the stop location, along with the ``Task``\ s - associated with the stop. Some fields of the VehicleStop - might not be present if this journey segment is part of - ``JourneySharingInfo``. - driving_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - Output only. The travel distance from the previous stop to - this stop. If the current stop is the first stop in the list - of journey segments, then the starting point is the - vehicle's location recorded at the time that this stop was - added to the list. This field might not be present if this - journey segment is part of ``JourneySharingInfo``. - driving_duration (google.protobuf.duration_pb2.Duration): - Output only. The travel time from the previous stop to this - stop. If the current stop is the first stop in the list of - journey segments, then the starting point is the Vehicle's - location recorded at the time that this stop was added to - the list. - - If this field is defined in the path - ``Task.remaining_vehicle_journey_segments[0].driving_duration`` - (gRPC) or - ``Task.remainingVehicleJourneySegments[0].drivingDuration`` - (REST), then it may be populated with the value from - ``DeliveryVehicle.remaining_duration`` (gRPC) or - ``DeliveryVehicle.remainingDuration`` (REST). This provides - the remaining driving duration from the driver app's latest - known location rather than the driving time from the - previous stop. - path (MutableSequence[google.type.latlng_pb2.LatLng]): - Output only. The path from the previous stop to this stop. - If the current stop is the first stop in the list of journey - segments, then this is the path from the vehicle's current - location to this stop at the time that the stop was added to - the list. This field might not be present if this journey - segment is part of ``JourneySharingInfo``. - - If this field is defined in the path - ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0].path`` - (gRPC) or - ``Task.journeySharingInfo.remainingVehicleJourneySegments[0].path`` - (REST), then it may be populated with the ``LatLng``\ s - decoded from ``DeliveryVehicle.current_route_segment`` - (gRPC) or ``DeliveryVehicle.currentRouteSegment`` (REST). - This provides the driving path from the driver app's latest - known location rather than the path from the previous stop. - """ - - stop: 'VehicleStop' = proto.Field( - proto.MESSAGE, - number=1, - message='VehicleStop', - ) - driving_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int32Value, - ) - driving_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=3, - message=duration_pb2.Duration, - ) - path: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=latlng_pb2.LatLng, - ) - - -class VehicleStop(proto.Message): - r"""Describes a point where a Vehicle stops to perform one or more - ``Task``\ s. - - Attributes: - planned_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): - Required. The location of the stop. Note that the locations - in the ``Task``\ s might not exactly match this location, - but will be within a short distance of it. This field won't - be populated in the response of a ``GetTask`` call. - tasks (MutableSequence[google.maps.fleetengine_delivery_v1.types.VehicleStop.TaskInfo]): - The list of ``Task``\ s to be performed at this stop. This - field won't be populated in the response of a ``GetTask`` - call. - state (google.maps.fleetengine_delivery_v1.types.VehicleStop.State): - The state of the ``VehicleStop``. This field won't be - populated in the response of a ``GetTask`` call. - """ - class State(proto.Enum): - r"""The current state of a ``VehicleStop``. - - Values: - STATE_UNSPECIFIED (0): - Unknown. - NEW (1): - Created, but not actively routing. - ENROUTE (2): - Assigned and actively routing. - ARRIVED (3): - Arrived at stop. Assumes that when the - Vehicle is routing to the next stop, that all - previous stops have been completed. - """ - STATE_UNSPECIFIED = 0 - NEW = 1 - ENROUTE = 2 - ARRIVED = 3 - - class TaskInfo(proto.Message): - r"""Additional information about the Task performed at this stop. - - Attributes: - task_id (str): - The Task ID. This field won't be populated in the response - of a ``GetTask`` call. Task IDs are 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 '#'. - task_duration (google.protobuf.duration_pb2.Duration): - Output only. The time required to perform the - Task. - target_time_window (google.maps.fleetengine_delivery_v1.types.TimeWindow): - Output only. The time window during which the task should be - completed. This is only set in the response to - ``GetDeliveryVehicle``. - """ - - task_id: str = proto.Field( - proto.STRING, - number=1, - ) - task_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - target_time_window: common.TimeWindow = proto.Field( - proto.MESSAGE, - number=3, - message=common.TimeWindow, - ) - - planned_location: 'LocationInfo' = proto.Field( - proto.MESSAGE, - number=1, - message='LocationInfo', - ) - tasks: MutableSequence[TaskInfo] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=TaskInfo, - ) - state: State = proto.Field( - proto.ENUM, - number=3, - enum=State, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/header.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/header.py deleted file mode 100644 index 4764c19a73c6..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_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.delivery.v1', - manifest={ - 'DeliveryRequestHeader', - }, -) - - -class DeliveryRequestHeader(proto.Message): - r"""A RequestHeader contains fields common to all Delivery 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_delivery_v1.types.DeliveryRequestHeader.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_delivery_v1.types.DeliveryRequestHeader.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-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.py deleted file mode 100644 index 8ad90dd9b068..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/task_tracking_info.py +++ /dev/null @@ -1,166 +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_delivery_v1.types import common -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import tasks -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.delivery.v1', - manifest={ - 'TaskTrackingInfo', - }, -) - - -class TaskTrackingInfo(proto.Message): - r"""The ``TaskTrackingInfo`` message. The message contains task tracking - information which will be used for display. If a tracking ID is - associated with multiple Tasks, Fleet Engine uses a heuristic to - decide which Task's TaskTrackingInfo to select. - - Attributes: - name (str): - Must be in the format - ``providers/{provider}/taskTrackingInfo/{tracking}``, where - ``tracking`` represents the tracking ID. - tracking_id (str): - Immutable. The tracking ID of a Task. - - - 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_location (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocation): - The vehicle's last location. - route_polyline_points (MutableSequence[google.type.latlng_pb2.LatLng]): - A list of points which when connected forms a - polyline of the vehicle's expected route to the - location of this task. - remaining_stop_count (google.protobuf.wrappers_pb2.Int32Value): - Indicates the number of stops the vehicle - remaining until the task stop is reached, - including the task stop. For example, if the - vehicle's next stop is the task stop, the value - will be 1. - remaining_driving_distance_meters (google.protobuf.wrappers_pb2.Int32Value): - The total remaining distance in meters to the - ``VehicleStop`` of interest. - estimated_arrival_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp that indicates the estimated - arrival time to the stop location. - estimated_task_completion_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp that indicates the estimated - completion time of a Task. - state (google.maps.fleetengine_delivery_v1.types.Task.State): - The current execution state of the Task. - task_outcome (google.maps.fleetengine_delivery_v1.types.Task.TaskOutcome): - The outcome of attempting to execute a Task. - task_outcome_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp that indicates when the Task's - outcome was set by the provider. - planned_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): - Immutable. The location where the Task will - be completed. - target_time_window (google.maps.fleetengine_delivery_v1.types.TimeWindow): - The time window during which the task should - be completed. - attributes (MutableSequence[google.maps.fleetengine_delivery_v1.types.TaskAttribute]): - The custom attributes set on the task. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - tracking_id: str = proto.Field( - proto.STRING, - number=2, - ) - vehicle_location: common.DeliveryVehicleLocation = proto.Field( - proto.MESSAGE, - number=3, - message=common.DeliveryVehicleLocation, - ) - route_polyline_points: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=latlng_pb2.LatLng, - ) - remaining_stop_count: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.Int32Value, - ) - remaining_driving_distance_meters: wrappers_pb2.Int32Value = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.Int32Value, - ) - estimated_arrival_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - estimated_task_completion_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - state: tasks.Task.State = proto.Field( - proto.ENUM, - number=11, - enum=tasks.Task.State, - ) - task_outcome: tasks.Task.TaskOutcome = proto.Field( - proto.ENUM, - number=9, - enum=tasks.Task.TaskOutcome, - ) - task_outcome_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - planned_location: delivery_vehicles.LocationInfo = proto.Field( - proto.MESSAGE, - number=10, - message=delivery_vehicles.LocationInfo, - ) - target_time_window: common.TimeWindow = proto.Field( - proto.MESSAGE, - number=13, - message=common.TimeWindow, - ) - attributes: MutableSequence[common.TaskAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=common.TaskAttribute, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.py deleted file mode 100644 index ecb26f920108..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/google/maps/fleetengine_delivery_v1/types/tasks.py +++ /dev/null @@ -1,473 +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_delivery_v1.types import common -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='maps.fleetengine.delivery.v1', - manifest={ - 'Task', - 'TaskTrackingViewConfig', - }, -) - - -class Task(proto.Message): - r"""A Task in the Delivery API represents a single action to track. In - general, there is a distinction between shipment-related Tasks and - break Tasks. A shipment can have multiple Tasks associated with it. - For example, there could be one Task for the pickup, and one for the - drop-off or transfer. Also, different Tasks for a given shipment can - be handled by different vehicles. For example, one vehicle could - handle the pickup, driving the shipment to the hub, while another - vehicle drives the same shipment from the hub to the drop-off - location. - - Note: gRPC and REST APIs use different field naming conventions. For - example, the ``Task.journey_sharing_info`` field in the gRPC API and - the ``Task.journeySharingInfo`` field in the REST API refer to the - same field. - - Attributes: - name (str): - Must be in the format ``providers/{provider}/tasks/{task}``. - type_ (google.maps.fleetengine_delivery_v1.types.Task.Type): - Required. Immutable. Defines the type of the - Task. For example, a break or shipment. - state (google.maps.fleetengine_delivery_v1.types.Task.State): - Required. The current execution state of the - Task. - task_outcome (google.maps.fleetengine_delivery_v1.types.Task.TaskOutcome): - The outcome of the Task. - task_outcome_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp that indicates when the ``Task``'s outcome was - set by the provider. - task_outcome_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): - The location where the ``Task``'s outcome was set. This - value is updated as part of ``UpdateTask``. If this value - isn't explicitly updated by the provider, then Fleet Engine - populates it by default with the last known vehicle location - (the *raw* location). - task_outcome_location_source (google.maps.fleetengine_delivery_v1.types.Task.TaskOutcomeLocationSource): - Indicates where the value of the ``task_outcome_location`` - came from. - tracking_id (str): - Immutable. This field facilitates the storing of an ID so - you can avoid using a complicated mapping. You cannot set - ``tracking_id`` for Tasks of type ``UNAVAILABLE`` and - ``SCHEDULED_STOP``. These IDs are 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 '#'. - delivery_vehicle_id (str): - Output only. The ID of the vehicle that is executing this - Task. Delivery Vehicle IDs are 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 '#'. - planned_location (google.maps.fleetengine_delivery_v1.types.LocationInfo): - Immutable. The location where the Task will be completed. - Optional for ``UNAVAILABLE`` Tasks, but required for all - other Tasks. - task_duration (google.protobuf.duration_pb2.Duration): - Required. Immutable. The time needed to - execute a Task at this location. - target_time_window (google.maps.fleetengine_delivery_v1.types.TimeWindow): - The time window during which the task should - be completed. - journey_sharing_info (google.maps.fleetengine_delivery_v1.types.Task.JourneySharingInfo): - Output only. Journey sharing-specific fields. Not populated - when state is ``CLOSED``. - task_tracking_view_config (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig): - The configuration for task tracking that - specifies which data elements are visible to the - end users under what circumstances. - attributes (MutableSequence[google.maps.fleetengine_delivery_v1.types.TaskAttribute]): - A list of custom Task attributes. Each - attribute must have a unique key. - """ - class Type(proto.Enum): - r"""The type of Task. - - Values: - TYPE_UNSPECIFIED (0): - Default, the Task type is unknown. - PICKUP (1): - A pickup Task is the action taken for picking up a shipment - from a customer. Depot or feeder vehicle pickups should use - the ``SCHEDULED_STOP`` type. - DELIVERY (2): - A delivery Task is the action taken for delivering a - shipment to an end customer. Depot or feeder vehicle - dropoffs should use the ``SCHEDULED_STOP`` type. - SCHEDULED_STOP (3): - A scheduled stop Task is used for planning - purposes. For example, it could represent - picking up or dropping off shipments from feeder - vehicles or depots. It shouldn't be used for any - shipments that are picked up or dropped off from - an end customer. - UNAVAILABLE (4): - A Task that means the Vehicle is not - available for service. For example, this can - happen when the driver takes a break, or when - the vehicle is being refueled. - """ - TYPE_UNSPECIFIED = 0 - PICKUP = 1 - DELIVERY = 2 - SCHEDULED_STOP = 3 - UNAVAILABLE = 4 - - class State(proto.Enum): - r"""The state of a Task. This indicates the Tasks's progress. - - Values: - STATE_UNSPECIFIED (0): - Default. Used for an unspecified or - unrecognized Task state. - OPEN (1): - Either the Task has not yet been assigned to a delivery - vehicle, or the delivery vehicle has not yet passed the - ``Task``'s assigned vehicle stop. - CLOSED (2): - When the vehicle passes the vehicle stop for - this Task. - """ - STATE_UNSPECIFIED = 0 - OPEN = 1 - CLOSED = 2 - - class TaskOutcome(proto.Enum): - r"""The outcome of attempting to execute a Task. When ``TaskState`` is - closed, ``TaskOutcome`` indicates whether it was completed - successfully. - - Values: - TASK_OUTCOME_UNSPECIFIED (0): - The Task outcome before its value is set. - SUCCEEDED (1): - The Task completed successfully. - FAILED (2): - Either the Task couldn't be completed, or it - was cancelled. - """ - TASK_OUTCOME_UNSPECIFIED = 0 - SUCCEEDED = 1 - FAILED = 2 - - class TaskOutcomeLocationSource(proto.Enum): - r"""The identity of the source that populated the - ``task_outcome_location``. - - Values: - TASK_OUTCOME_LOCATION_SOURCE_UNSPECIFIED (0): - The task outcome before it is set. - PROVIDER (2): - The provider-specified the ``task_outcome_location``. - LAST_VEHICLE_LOCATION (3): - The provider didn't specify the ``task_outcome_location``, - so Fleet Engine used the last known vehicle location. - """ - TASK_OUTCOME_LOCATION_SOURCE_UNSPECIFIED = 0 - PROVIDER = 2 - LAST_VEHICLE_LOCATION = 3 - - class JourneySharingInfo(proto.Message): - r"""Journey sharing specific fields. - - Attributes: - remaining_vehicle_journey_segments (MutableSequence[google.maps.fleetengine_delivery_v1.types.VehicleJourneySegment]): - Tracking information for the stops that the assigned vehicle - will make before it completes this Task. Note that this list - can contain stops from other tasks. - - The first segment, - ``Task.journey_sharing_info.remaining_vehicle_journey_segments[0]`` - (gRPC) or - ``Task.journeySharingInfo.remainingVehicleJourneySegments[0]`` - (REST), contains route information from the driver's last - known location to the upcoming ``VehicleStop``. Current - route information usually comes from the driver app, except - for some cases noted in the documentation for - [DeliveryVehicle.current_route_segment][maps.fleetengine.delivery.v1.DeliveryVehicle.current_route_segment]. - The other segments in - ``Task.journey_sharing_info.remaining_vehicle_journey_segments`` - (gRPC) or - ``Task.journeySharingInfo.remainingVehicleJourneySegments`` - (REST) are populated by Fleet Engine. They provide route - information between the remaining ``VehicleStops``. - last_location (google.maps.fleetengine_delivery_v1.types.DeliveryVehicleLocation): - Indicates the vehicle's last reported - location of the assigned vehicle. - last_location_snappable (bool): - Indicates whether the vehicle's lastLocation can be snapped - to the ``current_route_segment``. This value is False if - either ``last_location`` or ``current_route_segment`` don't - exist. This value is computed by Fleet Engine. Updates from - clients are ignored. - """ - - remaining_vehicle_journey_segments: MutableSequence[delivery_vehicles.VehicleJourneySegment] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=delivery_vehicles.VehicleJourneySegment, - ) - last_location: common.DeliveryVehicleLocation = proto.Field( - proto.MESSAGE, - number=2, - message=common.DeliveryVehicleLocation, - ) - last_location_snappable: bool = proto.Field( - proto.BOOL, - number=3, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - type_: Type = proto.Field( - proto.ENUM, - number=2, - enum=Type, - ) - state: State = proto.Field( - proto.ENUM, - number=3, - enum=State, - ) - task_outcome: TaskOutcome = proto.Field( - proto.ENUM, - number=9, - enum=TaskOutcome, - ) - task_outcome_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - task_outcome_location: delivery_vehicles.LocationInfo = proto.Field( - proto.MESSAGE, - number=11, - message=delivery_vehicles.LocationInfo, - ) - task_outcome_location_source: TaskOutcomeLocationSource = proto.Field( - proto.ENUM, - number=12, - enum=TaskOutcomeLocationSource, - ) - tracking_id: str = proto.Field( - proto.STRING, - number=4, - ) - delivery_vehicle_id: str = proto.Field( - proto.STRING, - number=5, - ) - planned_location: delivery_vehicles.LocationInfo = proto.Field( - proto.MESSAGE, - number=6, - message=delivery_vehicles.LocationInfo, - ) - task_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - target_time_window: common.TimeWindow = proto.Field( - proto.MESSAGE, - number=14, - message=common.TimeWindow, - ) - journey_sharing_info: JourneySharingInfo = proto.Field( - proto.MESSAGE, - number=8, - message=JourneySharingInfo, - ) - task_tracking_view_config: 'TaskTrackingViewConfig' = proto.Field( - proto.MESSAGE, - number=13, - message='TaskTrackingViewConfig', - ) - attributes: MutableSequence[common.TaskAttribute] = proto.RepeatedField( - proto.MESSAGE, - number=15, - message=common.TaskAttribute, - ) - - -class TaskTrackingViewConfig(proto.Message): - r"""The configuration message that defines when a data element of - a Task should be visible to the end users. - - Attributes: - route_polyline_points_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when route polyline - points can be visible. If this field is not - specified, the project level default visibility - configuration for this data will be used. - estimated_arrival_time_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when estimated - arrival time can be visible. If this field is - not specified, the project level default - visibility configuration for this data will be - used. - estimated_task_completion_time_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when estimated task - completion time can be visible. If this field is - not specified, the project level default - visibility configuration for this data will be - used. - remaining_driving_distance_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when remaining - driving distance can be visible. If this field - is not specified, the project level default - visibility configuration for this data will be - used. - remaining_stop_count_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when remaining stop - count can be visible. If this field is not - specified, the project level default visibility - configuration for this data will be used. - vehicle_location_visibility (google.maps.fleetengine_delivery_v1.types.TaskTrackingViewConfig.VisibilityOption): - The field that specifies when vehicle - location can be visible. If this field is not - specified, the project level default visibility - configuration for this data will be used. - """ - - class VisibilityOption(proto.Message): - r"""The option message that defines when a data element should be - visible to the end users. - - 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: - remaining_stop_count_threshold (int): - This data element is visible to the end users if the - remaining stop count <= remaining_stop_count_threshold. - - This field is a member of `oneof`_ ``visibility_option``. - duration_until_estimated_arrival_time_threshold (google.protobuf.duration_pb2.Duration): - This data element is visible to the end users if the ETA to - the stop <= duration_until_estimated_arrival_time_threshold. - - This field is a member of `oneof`_ ``visibility_option``. - remaining_driving_distance_meters_threshold (int): - This data element is visible to the end users if the - remaining driving distance in meters <= - remaining_driving_distance_meters_threshold. - - This field is a member of `oneof`_ ``visibility_option``. - always (bool): - If set to true, this data element is always - visible to the end users with no thresholds. - This field cannot be set to false. - - This field is a member of `oneof`_ ``visibility_option``. - never (bool): - If set to true, this data element is always - hidden from the end users with no thresholds. - This field cannot be set to false. - - This field is a member of `oneof`_ ``visibility_option``. - """ - - remaining_stop_count_threshold: int = proto.Field( - proto.INT32, - number=1, - oneof='visibility_option', - ) - duration_until_estimated_arrival_time_threshold: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - oneof='visibility_option', - message=duration_pb2.Duration, - ) - remaining_driving_distance_meters_threshold: int = proto.Field( - proto.INT32, - number=3, - oneof='visibility_option', - ) - always: bool = proto.Field( - proto.BOOL, - number=4, - oneof='visibility_option', - ) - never: bool = proto.Field( - proto.BOOL, - number=5, - oneof='visibility_option', - ) - - route_polyline_points_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=1, - message=VisibilityOption, - ) - estimated_arrival_time_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=2, - message=VisibilityOption, - ) - estimated_task_completion_time_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=3, - message=VisibilityOption, - ) - remaining_driving_distance_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=4, - message=VisibilityOption, - ) - remaining_stop_count_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=5, - message=VisibilityOption, - ) - vehicle_location_visibility: VisibilityOption = proto.Field( - proto.MESSAGE, - number=6, - message=VisibilityOption, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/mypy.ini b/owl-bot-staging/google-maps-fleetengine-delivery/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/noxfile.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/noxfile.py deleted file mode 100644 index 765885f9a3c2..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/noxfile.py +++ /dev/null @@ -1,278 +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" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-maps-fleetengine-delivery' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -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"): - 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_delivery_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"): - 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", - "grpcio", - "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_delivery_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-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py deleted file mode 100644 index 04dfa5f0bb70..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py +++ /dev/null @@ -1,59 +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 BatchCreateTasks -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_BatchCreateTasks_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_delivery_v1 - - -async def sample_batch_create_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - requests = fleetengine_delivery_v1.CreateTaskRequest() - requests.parent = "parent_value" - requests.task_id = "task_id_value" - requests.task.type_ = "UNAVAILABLE" - requests.task.state = "CLOSED" - - request = fleetengine_delivery_v1.BatchCreateTasksRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = await client.batch_create_tasks(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_BatchCreateTasks_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py deleted file mode 100644 index e22a2a94aeb1..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py +++ /dev/null @@ -1,59 +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 BatchCreateTasks -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_BatchCreateTasks_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_delivery_v1 - - -def sample_batch_create_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - requests = fleetengine_delivery_v1.CreateTaskRequest() - requests.parent = "parent_value" - requests.task_id = "task_id_value" - requests.task.type_ = "UNAVAILABLE" - requests.task.state = "CLOSED" - - request = fleetengine_delivery_v1.BatchCreateTasksRequest( - parent="parent_value", - requests=requests, - ) - - # Make the request - response = client.batch_create_tasks(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_BatchCreateTasks_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py deleted file mode 100644 index 0c37cfba37dd..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_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 CreateDeliveryVehicle -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_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_delivery_v1 - - -async def sample_create_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( - parent="parent_value", - delivery_vehicle_id="delivery_vehicle_id_value", - ) - - # Make the request - response = await client.create_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py deleted file mode 100644 index 2db42c6068e4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_delivery_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 CreateDeliveryVehicle -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_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_delivery_v1 - - -def sample_create_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.CreateDeliveryVehicleRequest( - parent="parent_value", - delivery_vehicle_id="delivery_vehicle_id_value", - ) - - # Make the request - response = client.create_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_async.py deleted file mode 100644 index 057d6ba4de47..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_async.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTask -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_CreateTask_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_delivery_v1 - - -async def sample_create_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.CreateTaskRequest( - parent="parent_value", - task_id="task_id_value", - task=task, - ) - - # Make the request - response = await client.create_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_CreateTask_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_sync.py deleted file mode 100644 index ab663bc61458..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_create_task_sync.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateTask -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_CreateTask_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_delivery_v1 - - -def sample_create_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.CreateTaskRequest( - parent="parent_value", - task_id="task_id_value", - task=task, - ) - - # Make the request - response = client.create_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_CreateTask_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py deleted file mode 100644 index 7ec99a4b6b6b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_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 GetDeliveryVehicle -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_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_delivery_v1 - - -async def sample_get_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py deleted file mode 100644 index 13994becb4b5..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_delivery_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 GetDeliveryVehicle -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_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_delivery_v1 - - -def sample_get_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetDeliveryVehicleRequest( - name="name_value", - ) - - # Make the request - response = client.get_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_async.py deleted file mode 100644 index 11afdf35a194..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_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 GetTask -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetTask_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_delivery_v1 - - -async def sample_get_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskRequest( - name="name_value", - ) - - # Make the request - response = await client.get_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetTask_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_sync.py deleted file mode 100644 index 47f7f5d20c3b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_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 GetTask -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetTask_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_delivery_v1 - - -def sample_get_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskRequest( - name="name_value", - ) - - # Make the request - response = client.get_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetTask_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py deleted file mode 100644 index e8f168c07e55..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_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 GetTaskTrackingInfo -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_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_delivery_v1 - - -async def sample_get_task_tracking_info(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( - name="name_value", - ) - - # Make the request - response = await client.get_task_tracking_info(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py deleted file mode 100644 index aac42ad23bd4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_get_task_tracking_info_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 GetTaskTrackingInfo -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_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_delivery_v1 - - -def sample_get_task_tracking_info(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.GetTaskTrackingInfoRequest( - name="name_value", - ) - - # Make the request - response = client.get_task_tracking_info(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py deleted file mode 100644 index 92cd353762c2..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_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 ListDeliveryVehicles -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_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_delivery_v1 - - -async def sample_list_delivery_vehicles(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_delivery_vehicles(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py deleted file mode 100644 index eb7f3d5332fa..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_delivery_vehicles_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 ListDeliveryVehicles -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_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_delivery_v1 - - -def sample_list_delivery_vehicles(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListDeliveryVehiclesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_delivery_vehicles(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_async.py deleted file mode 100644 index 5a75c67090bb..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_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 ListTasks -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_ListTasks_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_delivery_v1 - - -async def sample_list_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListTasksRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tasks(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END fleetengine_v1_generated_DeliveryService_ListTasks_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_sync.py deleted file mode 100644 index 5fa38d62c1fb..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_list_tasks_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 ListTasks -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_ListTasks_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_delivery_v1 - - -def sample_list_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.ListTasksRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_tasks(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END fleetengine_v1_generated_DeliveryService_ListTasks_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py deleted file mode 100644 index 48cb75ccb089..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_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 UpdateDeliveryVehicle -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_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_delivery_v1 - - -async def sample_update_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( - ) - - # Make the request - response = await client.update_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py deleted file mode 100644 index b79b67bf7ab0..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_delivery_vehicle_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 UpdateDeliveryVehicle -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_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_delivery_v1 - - -def sample_update_delivery_vehicle(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.UpdateDeliveryVehicleRequest( - ) - - # Make the request - response = client.update_delivery_vehicle(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_async.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_async.py deleted file mode 100644 index e5b4c9099c2f..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_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 UpdateTask -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_UpdateTask_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_delivery_v1 - - -async def sample_update_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.UpdateTaskRequest( - task=task, - ) - - # Make the request - response = await client.update_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_UpdateTask_async] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_sync.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_sync.py deleted file mode 100644 index cdb247237fa2..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/fleetengine_v1_generated_delivery_service_update_task_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 UpdateTask -# 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-delivery - - -# [START fleetengine_v1_generated_DeliveryService_UpdateTask_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_delivery_v1 - - -def sample_update_task(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - task = fleetengine_delivery_v1.Task() - task.type_ = "UNAVAILABLE" - task.state = "CLOSED" - - request = fleetengine_delivery_v1.UpdateTaskRequest( - task=task, - ) - - # Make the request - response = client.update_task(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_DeliveryService_UpdateTask_sync] diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json b/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json deleted file mode 100644 index 884ac226d0e4..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json +++ /dev/null @@ -1,1665 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "maps.fleetengine.delivery.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-maps-fleetengine-delivery", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.batch_create_tasks", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.BatchCreateTasks", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "BatchCreateTasks" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksResponse", - "shortName": "batch_create_tasks" - }, - "description": "Sample for BatchCreateTasks", - "file": "fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_BatchCreateTasks_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_delivery_service_batch_create_tasks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.batch_create_tasks", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.BatchCreateTasks", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "BatchCreateTasks" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.BatchCreateTasksResponse", - "shortName": "batch_create_tasks" - }, - "description": "Sample for BatchCreateTasks", - "file": "fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_BatchCreateTasks_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_delivery_service_batch_create_tasks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.create_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "CreateDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "delivery_vehicle", - "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" - }, - { - "name": "delivery_vehicle_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "create_delivery_vehicle" - }, - "description": "Sample for CreateDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_create_delivery_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_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_delivery_service_create_delivery_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.create_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "CreateDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.CreateDeliveryVehicleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "delivery_vehicle", - "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" - }, - { - "name": "delivery_vehicle_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "create_delivery_vehicle" - }, - "description": "Sample for CreateDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_create_delivery_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_CreateDeliveryVehicle_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_delivery_service_create_delivery_vehicle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.create_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "CreateTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.CreateTaskRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "task", - "type": "google.maps.fleetengine_delivery_v1.types.Task" - }, - { - "name": "task_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "create_task" - }, - "description": "Sample for CreateTask", - "file": "fleetengine_v1_generated_delivery_service_create_task_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_CreateTask_async", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_delivery_service_create_task_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.create_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.CreateTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "CreateTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.CreateTaskRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "task", - "type": "google.maps.fleetengine_delivery_v1.types.Task" - }, - { - "name": "task_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "create_task" - }, - "description": "Sample for CreateTask", - "file": "fleetengine_v1_generated_delivery_service_create_task_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_CreateTask_sync", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_delivery_service_create_task_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.get_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "get_delivery_vehicle" - }, - "description": "Sample for GetDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_get_delivery_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_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_delivery_service_get_delivery_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.get_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetDeliveryVehicleRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "get_delivery_vehicle" - }, - "description": "Sample for GetDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_get_delivery_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetDeliveryVehicle_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_delivery_service_get_delivery_vehicle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.get_task_tracking_info", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTaskTrackingInfo", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetTaskTrackingInfo" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.TaskTrackingInfo", - "shortName": "get_task_tracking_info" - }, - "description": "Sample for GetTaskTrackingInfo", - "file": "fleetengine_v1_generated_delivery_service_get_task_tracking_info_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_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_delivery_service_get_task_tracking_info_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.get_task_tracking_info", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTaskTrackingInfo", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetTaskTrackingInfo" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetTaskTrackingInfoRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.TaskTrackingInfo", - "shortName": "get_task_tracking_info" - }, - "description": "Sample for GetTaskTrackingInfo", - "file": "fleetengine_v1_generated_delivery_service_get_task_tracking_info_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetTaskTrackingInfo_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_delivery_service_get_task_tracking_info_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.get_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetTaskRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "get_task" - }, - "description": "Sample for GetTask", - "file": "fleetengine_v1_generated_delivery_service_get_task_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetTask_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_delivery_service_get_task_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.get_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.GetTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "GetTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.GetTaskRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "get_task" - }, - "description": "Sample for GetTask", - "file": "fleetengine_v1_generated_delivery_service_get_task_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_GetTask_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_delivery_service_get_task_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.list_delivery_vehicles", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListDeliveryVehicles", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "ListDeliveryVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesAsyncPager", - "shortName": "list_delivery_vehicles" - }, - "description": "Sample for ListDeliveryVehicles", - "file": "fleetengine_v1_generated_delivery_service_list_delivery_vehicles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_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_delivery_service_list_delivery_vehicles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.list_delivery_vehicles", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListDeliveryVehicles", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "ListDeliveryVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.ListDeliveryVehiclesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListDeliveryVehiclesPager", - "shortName": "list_delivery_vehicles" - }, - "description": "Sample for ListDeliveryVehicles", - "file": "fleetengine_v1_generated_delivery_service_list_delivery_vehicles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_ListDeliveryVehicles_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_delivery_service_list_delivery_vehicles_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.list_tasks", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListTasks", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "ListTasks" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.ListTasksRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListTasksAsyncPager", - "shortName": "list_tasks" - }, - "description": "Sample for ListTasks", - "file": "fleetengine_v1_generated_delivery_service_list_tasks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_ListTasks_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_delivery_service_list_tasks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.list_tasks", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.ListTasks", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "ListTasks" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.ListTasksRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.ListTasksPager", - "shortName": "list_tasks" - }, - "description": "Sample for ListTasks", - "file": "fleetengine_v1_generated_delivery_service_list_tasks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_ListTasks_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_delivery_service_list_tasks_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.update_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "UpdateDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest" - }, - { - "name": "delivery_vehicle", - "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "update_delivery_vehicle" - }, - "description": "Sample for UpdateDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.update_delivery_vehicle", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateDeliveryVehicle", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "UpdateDeliveryVehicle" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.UpdateDeliveryVehicleRequest" - }, - { - "name": "delivery_vehicle", - "type": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.DeliveryVehicle", - "shortName": "update_delivery_vehicle" - }, - "description": "Sample for UpdateDeliveryVehicle", - "file": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateDeliveryVehicle_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_delivery_service_update_delivery_vehicle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.update_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "UpdateTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest" - }, - { - "name": "task", - "type": "google.maps.fleetengine_delivery_v1.types.Task" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "update_task" - }, - "description": "Sample for UpdateTask", - "file": "fleetengine_v1_generated_delivery_service_update_task_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateTask_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_delivery_service_update_task_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.update_task", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.UpdateTask", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "UpdateTask" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.UpdateTaskRequest" - }, - { - "name": "task", - "type": "google.maps.fleetengine_delivery_v1.types.Task" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.types.Task", - "shortName": "update_task" - }, - "description": "Sample for UpdateTask", - "file": "fleetengine_v1_generated_delivery_service_update_task_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_UpdateTask_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_delivery_service_update_task_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py deleted file mode 100644 index 8dc89e72edee..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/scripts/fixup_fleetengine_delivery_v1_keywords.py +++ /dev/null @@ -1,185 +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 fleetengine_deliveryCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_create_tasks': ('parent', 'requests', 'header', ), - 'create_delivery_vehicle': ('parent', 'delivery_vehicle_id', 'delivery_vehicle', 'header', ), - 'create_task': ('parent', 'task_id', 'task', 'header', ), - 'get_delivery_vehicle': ('name', 'header', ), - 'get_task': ('name', 'header', ), - 'get_task_tracking_info': ('name', 'header', ), - 'list_delivery_vehicles': ('parent', 'header', 'page_size', 'page_token', 'filter', 'viewport', ), - 'list_tasks': ('parent', 'header', 'page_size', 'page_token', 'filter', ), - 'update_delivery_vehicle': ('delivery_vehicle', 'update_mask', 'header', ), - 'update_task': ('task', 'update_mask', '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=fleetengine_deliveryCallTransformer(), -): - """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_delivery 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-delivery/v1/setup.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/setup.py deleted file mode 100644 index b91ec1fdae2b..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/setup.py +++ /dev/null @@ -1,94 +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-delivery' - - -description = "Google Maps Fleetengine Delivery API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/fleetengine_delivery/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", - "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", -] -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine-delivery" - -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.10.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.11.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.12.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.7.txt deleted file mode 100644 index 277853c664a0..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.8.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-fleetengine-delivery/v1/testing/constraints-3.9.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/tests/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/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-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/__init__.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_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-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py b/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py deleted file mode 100644 index 356bb85a4fec..000000000000 --- a/owl-bot-staging/google-maps-fleetengine-delivery/v1/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py +++ /dev/null @@ -1,8277 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -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_delivery_v1.services.delivery_service import DeliveryServiceAsyncClient -from google.maps.fleetengine_delivery_v1.services.delivery_service import DeliveryServiceClient -from google.maps.fleetengine_delivery_v1.services.delivery_service import pagers -from google.maps.fleetengine_delivery_v1.services.delivery_service import transports -from google.maps.fleetengine_delivery_v1.types import common -from google.maps.fleetengine_delivery_v1.types import delivery_api -from google.maps.fleetengine_delivery_v1.types import delivery_vehicles -from google.maps.fleetengine_delivery_v1.types import header -from google.maps.fleetengine_delivery_v1.types import task_tracking_info -from google.maps.fleetengine_delivery_v1.types import tasks -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 - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# 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 DeliveryServiceClient._get_default_mtls_endpoint(None) is None - assert DeliveryServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DeliveryServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DeliveryServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DeliveryServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DeliveryServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert DeliveryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert DeliveryServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert DeliveryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - DeliveryServiceClient._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 DeliveryServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert DeliveryServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert DeliveryServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - DeliveryServiceClient._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 DeliveryServiceClient._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 DeliveryServiceClient._get_client_cert_source(None, False) is None - assert DeliveryServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert DeliveryServiceClient._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 DeliveryServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert DeliveryServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) -@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = DeliveryServiceClient._DEFAULT_UNIVERSE - default_endpoint = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert DeliveryServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert DeliveryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT - assert DeliveryServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert DeliveryServiceClient._get_api_endpoint(None, None, default_universe, "always") == DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT - assert DeliveryServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DeliveryServiceClient.DEFAULT_MTLS_ENDPOINT - assert DeliveryServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert DeliveryServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - DeliveryServiceClient._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 DeliveryServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert DeliveryServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert DeliveryServiceClient._get_universe_domain(None, None) == DeliveryServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - DeliveryServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc"), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DeliveryServiceClient, "grpc"), - (DeliveryServiceAsyncClient, "grpc_asyncio"), - (DeliveryServiceClient, "rest"), -]) -def test_delivery_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' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://fleetengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DeliveryServiceGrpcTransport, "grpc"), - (transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DeliveryServiceRestTransport, "rest"), -]) -def test_delivery_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", [ - (DeliveryServiceClient, "grpc"), - (DeliveryServiceAsyncClient, "grpc_asyncio"), - (DeliveryServiceClient, "rest"), -]) -def test_delivery_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' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://fleetengine.googleapis.com' - ) - - -def test_delivery_service_client_get_transport_class(): - transport = DeliveryServiceClient.get_transport_class() - available_transports = [ - transports.DeliveryServiceGrpcTransport, - transports.DeliveryServiceRestTransport, - ] - assert transport in available_transports - - transport = DeliveryServiceClient.get_transport_class("grpc") - assert transport == transports.DeliveryServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc"), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest"), -]) -@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) -@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) -def test_delivery_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(DeliveryServiceClient, '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(DeliveryServiceClient, '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", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", "true"), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", "false"), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest", "true"), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) -@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_delivery_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", [ - DeliveryServiceClient, DeliveryServiceAsyncClient -]) -@mock.patch.object(DeliveryServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeliveryServiceClient)) -@mock.patch.object(DeliveryServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeliveryServiceAsyncClient)) -def test_delivery_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", [ - DeliveryServiceClient, DeliveryServiceAsyncClient -]) -@mock.patch.object(DeliveryServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceClient)) -@mock.patch.object(DeliveryServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeliveryServiceAsyncClient)) -def test_delivery_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = DeliveryServiceClient._DEFAULT_UNIVERSE - default_endpoint = DeliveryServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = DeliveryServiceClient._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", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc"), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest"), -]) -def test_delivery_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", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", grpc_helpers), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DeliveryServiceClient, transports.DeliveryServiceRestTransport, "rest", None), -]) -def test_delivery_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_delivery_service_client_client_options_from_dict(): - with mock.patch('google.maps.fleetengine_delivery_v1.services.delivery_service.transports.DeliveryServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DeliveryServiceClient( - 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", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport, "grpc", grpc_helpers), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_delivery_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", [ - delivery_api.CreateDeliveryVehicleRequest, - dict, -]) -def test_create_delivery_vehicle(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - response = client.create_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.CreateDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -def test_create_delivery_vehicle_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_delivery_vehicle() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.CreateDeliveryVehicleRequest() - - -def test_create_delivery_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 = DeliveryServiceClient( - 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 = delivery_api.CreateDeliveryVehicleRequest( - parent='parent_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_delivery_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.CreateDeliveryVehicleRequest( - parent='parent_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - -def test_create_delivery_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 = DeliveryServiceClient( - 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_delivery_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_delivery_vehicle] = mock_rpc - request = {} - client.create_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_delivery_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_delivery_vehicle_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - response = await client.create_delivery_vehicle() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.CreateDeliveryVehicleRequest() - -@pytest.mark.asyncio -async def test_create_delivery_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 = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_delivery_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_delivery_vehicle] = mock_rpc - - request = {} - await client.create_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_delivery_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_delivery_vehicle_async(transport: str = 'grpc_asyncio', request_type=delivery_api.CreateDeliveryVehicleRequest): - client = DeliveryServiceAsyncClient( - 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - response = await client.create_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.CreateDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -@pytest.mark.asyncio -async def test_create_delivery_vehicle_async_from_dict(): - await test_create_delivery_vehicle_async(request_type=dict) - -def test_create_delivery_vehicle_routing_parameters(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = delivery_api.CreateDeliveryVehicleRequest(**{"parent": "providers/sample1"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - call.return_value = delivery_vehicles.DeliveryVehicle() - client.create_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_create_delivery_vehicle_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_delivery_vehicle( - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].delivery_vehicle - mock_val = delivery_vehicles.DeliveryVehicle(name='name_value') - assert arg == mock_val - arg = args[0].delivery_vehicle_id - mock_val = 'delivery_vehicle_id_value' - assert arg == mock_val - - -def test_create_delivery_vehicle_flattened_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_delivery_vehicle( - delivery_api.CreateDeliveryVehicleRequest(), - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_id_value', - ) - -@pytest.mark.asyncio -async def test_create_delivery_vehicle_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_delivery_vehicle( - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].delivery_vehicle - mock_val = delivery_vehicles.DeliveryVehicle(name='name_value') - assert arg == mock_val - arg = args[0].delivery_vehicle_id - mock_val = 'delivery_vehicle_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_delivery_vehicle_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_delivery_vehicle( - delivery_api.CreateDeliveryVehicleRequest(), - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.GetDeliveryVehicleRequest, - dict, -]) -def test_get_delivery_vehicle(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - response = client.get_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.GetDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -def test_get_delivery_vehicle_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_delivery_vehicle() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetDeliveryVehicleRequest() - - -def test_get_delivery_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 = DeliveryServiceClient( - 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 = delivery_api.GetDeliveryVehicleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_delivery_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetDeliveryVehicleRequest( - name='name_value', - ) - -def test_get_delivery_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 = DeliveryServiceClient( - 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_delivery_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_delivery_vehicle] = mock_rpc - request = {} - client.get_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_delivery_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_delivery_vehicle_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - response = await client.get_delivery_vehicle() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetDeliveryVehicleRequest() - -@pytest.mark.asyncio -async def test_get_delivery_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 = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_delivery_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_delivery_vehicle] = mock_rpc - - request = {} - await client.get_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_delivery_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_delivery_vehicle_async(transport: str = 'grpc_asyncio', request_type=delivery_api.GetDeliveryVehicleRequest): - client = DeliveryServiceAsyncClient( - 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - response = await client.get_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.GetDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -@pytest.mark.asyncio -async def test_get_delivery_vehicle_async_from_dict(): - await test_get_delivery_vehicle_async(request_type=dict) - -def test_get_delivery_vehicle_routing_parameters(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = delivery_api.GetDeliveryVehicleRequest(**{"name": "providers/sample1"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - call.return_value = delivery_vehicles.DeliveryVehicle() - client.get_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_get_delivery_vehicle_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_delivery_vehicle( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_delivery_vehicle_flattened_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_delivery_vehicle( - delivery_api.GetDeliveryVehicleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_delivery_vehicle_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_delivery_vehicle( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_delivery_vehicle_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_delivery_vehicle( - delivery_api.GetDeliveryVehicleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.UpdateDeliveryVehicleRequest, - dict, -]) -def test_update_delivery_vehicle(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - response = client.update_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.UpdateDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -def test_update_delivery_vehicle_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_delivery_vehicle() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.UpdateDeliveryVehicleRequest() - - -def test_update_delivery_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 = DeliveryServiceClient( - 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 = delivery_api.UpdateDeliveryVehicleRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_delivery_vehicle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.UpdateDeliveryVehicleRequest( - ) - -def test_update_delivery_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 = DeliveryServiceClient( - 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_delivery_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_delivery_vehicle] = mock_rpc - request = {} - client.update_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_delivery_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_delivery_vehicle_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - response = await client.update_delivery_vehicle() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.UpdateDeliveryVehicleRequest() - -@pytest.mark.asyncio -async def test_update_delivery_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 = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_delivery_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_delivery_vehicle] = mock_rpc - - request = {} - await client.update_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_delivery_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_delivery_vehicle_async(transport: str = 'grpc_asyncio', request_type=delivery_api.UpdateDeliveryVehicleRequest): - client = DeliveryServiceAsyncClient( - 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_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - )) - response = await client.update_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.UpdateDeliveryVehicleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -@pytest.mark.asyncio -async def test_update_delivery_vehicle_async_from_dict(): - await test_update_delivery_vehicle_async(request_type=dict) - -def test_update_delivery_vehicle_routing_parameters(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = delivery_api.UpdateDeliveryVehicleRequest(**{"delivery_vehicle": {"name": "providers/sample1"}}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - call.return_value = delivery_vehicles.DeliveryVehicle() - client.update_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_update_delivery_vehicle_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_delivery_vehicle( - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].delivery_vehicle - mock_val = delivery_vehicles.DeliveryVehicle(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_delivery_vehicle_flattened_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_delivery_vehicle( - delivery_api.UpdateDeliveryVehicleRequest(), - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_delivery_vehicle_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_delivery_vehicle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_vehicles.DeliveryVehicle() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_vehicles.DeliveryVehicle()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_delivery_vehicle( - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].delivery_vehicle - mock_val = delivery_vehicles.DeliveryVehicle(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_delivery_vehicle_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_delivery_vehicle( - delivery_api.UpdateDeliveryVehicleRequest(), - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.BatchCreateTasksRequest, - dict, -]) -def test_batch_create_tasks(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - 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.batch_create_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.BatchCreateTasksResponse( - ) - response = client.batch_create_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.BatchCreateTasksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_api.BatchCreateTasksResponse) - - -def test_batch_create_tasks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_tasks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_tasks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.BatchCreateTasksRequest() - - -def test_batch_create_tasks_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 = DeliveryServiceClient( - 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 = delivery_api.BatchCreateTasksRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_tasks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.batch_create_tasks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.BatchCreateTasksRequest( - parent='parent_value', - ) - -def test_batch_create_tasks_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 = DeliveryServiceClient( - 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.batch_create_tasks 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.batch_create_tasks] = mock_rpc - request = {} - client.batch_create_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_tasks(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_batch_create_tasks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.BatchCreateTasksResponse( - )) - response = await client.batch_create_tasks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.BatchCreateTasksRequest() - -@pytest.mark.asyncio -async def test_batch_create_tasks_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 = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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.batch_create_tasks 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.batch_create_tasks] = mock_rpc - - request = {} - await client.batch_create_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.batch_create_tasks(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_batch_create_tasks_async(transport: str = 'grpc_asyncio', request_type=delivery_api.BatchCreateTasksRequest): - client = DeliveryServiceAsyncClient( - 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.batch_create_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.BatchCreateTasksResponse( - )) - response = await client.batch_create_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.BatchCreateTasksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_api.BatchCreateTasksResponse) - - -@pytest.mark.asyncio -async def test_batch_create_tasks_async_from_dict(): - await test_batch_create_tasks_async(request_type=dict) - -def test_batch_create_tasks_routing_parameters(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = delivery_api.BatchCreateTasksRequest(**{"parent": "providers/sample1"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_tasks), - '__call__') as call: - call.return_value = delivery_api.BatchCreateTasksResponse() - client.batch_create_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - delivery_api.CreateTaskRequest, - dict, -]) -def test_create_task(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - response = client.create_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.CreateTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -def test_create_task_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_task() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.CreateTaskRequest() - - -def test_create_task_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 = DeliveryServiceClient( - 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 = delivery_api.CreateTaskRequest( - parent='parent_value', - task_id='task_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_task(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.CreateTaskRequest( - parent='parent_value', - task_id='task_id_value', - ) - -def test_create_task_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 = DeliveryServiceClient( - 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_task 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_task] = mock_rpc - request = {} - client.create_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_task(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_task_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - response = await client.create_task() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.CreateTaskRequest() - -@pytest.mark.asyncio -async def test_create_task_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 = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_task 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_task] = mock_rpc - - request = {} - await client.create_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_task(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_task_async(transport: str = 'grpc_asyncio', request_type=delivery_api.CreateTaskRequest): - client = DeliveryServiceAsyncClient( - 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - response = await client.create_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.CreateTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -@pytest.mark.asyncio -async def test_create_task_async_from_dict(): - await test_create_task_async(request_type=dict) - -def test_create_task_routing_parameters(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = delivery_api.CreateTaskRequest(**{"parent": "providers/sample1"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - call.return_value = tasks.Task() - client.create_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_create_task_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_task( - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].task - mock_val = tasks.Task(name='name_value') - assert arg == mock_val - arg = args[0].task_id - mock_val = 'task_id_value' - assert arg == mock_val - - -def test_create_task_flattened_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_task( - delivery_api.CreateTaskRequest(), - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_id_value', - ) - -@pytest.mark.asyncio -async def test_create_task_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_task( - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].task - mock_val = tasks.Task(name='name_value') - assert arg == mock_val - arg = args[0].task_id - mock_val = 'task_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_task_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_task( - delivery_api.CreateTaskRequest(), - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.GetTaskRequest, - dict, -]) -def test_get_task(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - response = client.get_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.GetTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -def test_get_task_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_task() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetTaskRequest() - - -def test_get_task_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 = DeliveryServiceClient( - 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 = delivery_api.GetTaskRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_task(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetTaskRequest( - name='name_value', - ) - -def test_get_task_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 = DeliveryServiceClient( - 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_task 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_task] = mock_rpc - request = {} - client.get_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_task(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_task_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - response = await client.get_task() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetTaskRequest() - -@pytest.mark.asyncio -async def test_get_task_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 = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_task 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_task] = mock_rpc - - request = {} - await client.get_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_task(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_task_async(transport: str = 'grpc_asyncio', request_type=delivery_api.GetTaskRequest): - client = DeliveryServiceAsyncClient( - 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - response = await client.get_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.GetTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -@pytest.mark.asyncio -async def test_get_task_async_from_dict(): - await test_get_task_async(request_type=dict) - -def test_get_task_routing_parameters(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = delivery_api.GetTaskRequest(**{"name": "providers/sample1"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - call.return_value = tasks.Task() - client.get_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_get_task_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_task( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_task_flattened_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_task( - delivery_api.GetTaskRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_task_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_task( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_task_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_task( - delivery_api.GetTaskRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.UpdateTaskRequest, - dict, -]) -def test_update_task(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - response = client.update_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.UpdateTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -def test_update_task_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_task() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.UpdateTaskRequest() - - -def test_update_task_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 = DeliveryServiceClient( - 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 = delivery_api.UpdateTaskRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_task(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.UpdateTaskRequest( - ) - -def test_update_task_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 = DeliveryServiceClient( - 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_task 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_task] = mock_rpc - request = {} - client.update_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_task(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_task_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - response = await client.update_task() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.UpdateTaskRequest() - -@pytest.mark.asyncio -async def test_update_task_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 = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_task 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_task] = mock_rpc - - request = {} - await client.update_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_task(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_task_async(transport: str = 'grpc_asyncio', request_type=delivery_api.UpdateTaskRequest): - client = DeliveryServiceAsyncClient( - 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_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - )) - response = await client.update_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.UpdateTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - - -@pytest.mark.asyncio -async def test_update_task_async_from_dict(): - await test_update_task_async(request_type=dict) - -def test_update_task_routing_parameters(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = delivery_api.UpdateTaskRequest(**{"task": {"name": "providers/sample1"}}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - call.return_value = tasks.Task() - client.update_task(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_update_task_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_task( - task=tasks.Task(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].task - mock_val = tasks.Task(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_task_flattened_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_task( - delivery_api.UpdateTaskRequest(), - task=tasks.Task(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_task_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_task), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_task( - task=tasks.Task(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].task - mock_val = tasks.Task(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_task_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_task( - delivery_api.UpdateTaskRequest(), - task=tasks.Task(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.ListTasksRequest, - dict, -]) -def test_list_tasks(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - 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_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListTasksResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.ListTasksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_tasks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_tasks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.ListTasksRequest() - - -def test_list_tasks_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 = DeliveryServiceClient( - 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 = delivery_api.ListTasksRequest( - 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_tasks), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_tasks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.ListTasksRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - -def test_list_tasks_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 = DeliveryServiceClient( - 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_tasks 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_tasks] = mock_rpc - request = {} - client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_tasks(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_tasks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListTasksResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_tasks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.ListTasksRequest() - -@pytest.mark.asyncio -async def test_list_tasks_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 = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_tasks 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_tasks] = mock_rpc - - request = {} - await client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_tasks(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_tasks_async(transport: str = 'grpc_asyncio', request_type=delivery_api.ListTasksRequest): - client = DeliveryServiceAsyncClient( - 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_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListTasksResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.ListTasksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_tasks_async_from_dict(): - await test_list_tasks_async(request_type=dict) - -def test_list_tasks_routing_parameters(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = delivery_api.ListTasksRequest(**{"parent": "providers/sample1"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - call.return_value = delivery_api.ListTasksResponse() - client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_list_tasks_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListTasksResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_tasks( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_tasks_flattened_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_tasks( - delivery_api.ListTasksRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_tasks_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListTasksResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListTasksResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_tasks( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_tasks_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_tasks( - delivery_api.ListTasksRequest(), - parent='parent_value', - ) - - -def test_list_tasks_pager(transport_name: str = "grpc"): - client = DeliveryServiceClient( - 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_tasks), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token='abc', - ), - delivery_api.ListTasksResponse( - tasks=[], - next_page_token='def', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token='ghi', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_tasks(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, tasks.Task) - for i in results) -def test_list_tasks_pages(transport_name: str = "grpc"): - client = DeliveryServiceClient( - 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_tasks), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token='abc', - ), - delivery_api.ListTasksResponse( - tasks=[], - next_page_token='def', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token='ghi', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - RuntimeError, - ) - pages = list(client.list_tasks(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_tasks_async_pager(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token='abc', - ), - delivery_api.ListTasksResponse( - tasks=[], - next_page_token='def', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token='ghi', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_tasks(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, tasks.Task) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_tasks_async_pages(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_tasks), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token='abc', - ), - delivery_api.ListTasksResponse( - tasks=[], - next_page_token='def', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token='ghi', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - 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_tasks(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", [ - delivery_api.GetTaskTrackingInfoRequest, - dict, -]) -def test_get_task_tracking_info(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - 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_task_tracking_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = task_tracking_info.TaskTrackingInfo( - name='name_value', - tracking_id='tracking_id_value', - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - ) - response = client.get_task_tracking_info(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.GetTaskTrackingInfoRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, task_tracking_info.TaskTrackingInfo) - assert response.name == 'name_value' - assert response.tracking_id == 'tracking_id_value' - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - - -def test_get_task_tracking_info_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_task_tracking_info() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetTaskTrackingInfoRequest() - - -def test_get_task_tracking_info_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 = DeliveryServiceClient( - 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 = delivery_api.GetTaskTrackingInfoRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_task_tracking_info(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetTaskTrackingInfoRequest( - name='name_value', - ) - -def test_get_task_tracking_info_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 = DeliveryServiceClient( - 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_task_tracking_info 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_task_tracking_info] = mock_rpc - request = {} - client.get_task_tracking_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_task_tracking_info(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_task_tracking_info_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task_tracking_info.TaskTrackingInfo( - name='name_value', - tracking_id='tracking_id_value', - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - )) - response = await client.get_task_tracking_info() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.GetTaskTrackingInfoRequest() - -@pytest.mark.asyncio -async def test_get_task_tracking_info_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 = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_task_tracking_info 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_task_tracking_info] = mock_rpc - - request = {} - await client.get_task_tracking_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_task_tracking_info(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_task_tracking_info_async(transport: str = 'grpc_asyncio', request_type=delivery_api.GetTaskTrackingInfoRequest): - client = DeliveryServiceAsyncClient( - 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_task_tracking_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(task_tracking_info.TaskTrackingInfo( - name='name_value', - tracking_id='tracking_id_value', - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - )) - response = await client.get_task_tracking_info(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.GetTaskTrackingInfoRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, task_tracking_info.TaskTrackingInfo) - assert response.name == 'name_value' - assert response.tracking_id == 'tracking_id_value' - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - - -@pytest.mark.asyncio -async def test_get_task_tracking_info_async_from_dict(): - await test_get_task_tracking_info_async(request_type=dict) - -def test_get_task_tracking_info_routing_parameters(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = delivery_api.GetTaskTrackingInfoRequest(**{"name": "providers/sample1"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - call.return_value = task_tracking_info.TaskTrackingInfo() - client.get_task_tracking_info(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_get_task_tracking_info_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = task_tracking_info.TaskTrackingInfo() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_task_tracking_info( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_task_tracking_info_flattened_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_task_tracking_info( - delivery_api.GetTaskTrackingInfoRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_task_tracking_info_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_task_tracking_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = task_tracking_info.TaskTrackingInfo() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(task_tracking_info.TaskTrackingInfo()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_task_tracking_info( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_task_tracking_info_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_task_tracking_info( - delivery_api.GetTaskTrackingInfoRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.ListDeliveryVehiclesRequest, - dict, -]) -def test_list_delivery_vehicles(request_type, transport: str = 'grpc'): - client = DeliveryServiceClient( - 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_delivery_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListDeliveryVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_delivery_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.ListDeliveryVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeliveryVehiclesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_delivery_vehicles_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_delivery_vehicles() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.ListDeliveryVehiclesRequest() - - -def test_list_delivery_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 = DeliveryServiceClient( - 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 = delivery_api.ListDeliveryVehiclesRequest( - 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_delivery_vehicles), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_delivery_vehicles(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.ListDeliveryVehiclesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - -def test_list_delivery_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 = DeliveryServiceClient( - 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_delivery_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_delivery_vehicles] = mock_rpc - request = {} - client.list_delivery_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_delivery_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_delivery_vehicles_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListDeliveryVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_delivery_vehicles() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.ListDeliveryVehiclesRequest() - -@pytest.mark.asyncio -async def test_list_delivery_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 = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_delivery_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_delivery_vehicles] = mock_rpc - - request = {} - await client.list_delivery_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_delivery_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_delivery_vehicles_async(transport: str = 'grpc_asyncio', request_type=delivery_api.ListDeliveryVehiclesRequest): - client = DeliveryServiceAsyncClient( - 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_delivery_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListDeliveryVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_delivery_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.ListDeliveryVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeliveryVehiclesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_delivery_vehicles_async_from_dict(): - await test_list_delivery_vehicles_async(request_type=dict) - -def test_list_delivery_vehicles_routing_parameters(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = delivery_api.ListDeliveryVehiclesRequest(**{"parent": "providers/sample1"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - call.return_value = delivery_api.ListDeliveryVehiclesResponse() - client.list_delivery_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw['metadata'] - - -def test_list_delivery_vehicles_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListDeliveryVehiclesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_delivery_vehicles( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_delivery_vehicles_flattened_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_delivery_vehicles( - delivery_api.ListDeliveryVehiclesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_delivery_vehicles_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListDeliveryVehiclesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(delivery_api.ListDeliveryVehiclesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_delivery_vehicles( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_delivery_vehicles_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_delivery_vehicles( - delivery_api.ListDeliveryVehiclesRequest(), - parent='parent_value', - ) - - -def test_list_delivery_vehicles_pager(transport_name: str = "grpc"): - client = DeliveryServiceClient( - 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_delivery_vehicles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='abc', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[], - next_page_token='def', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='ghi', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_delivery_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, delivery_vehicles.DeliveryVehicle) - for i in results) -def test_list_delivery_vehicles_pages(transport_name: str = "grpc"): - client = DeliveryServiceClient( - 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_delivery_vehicles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='abc', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[], - next_page_token='def', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='ghi', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - ), - RuntimeError, - ) - pages = list(client.list_delivery_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_delivery_vehicles_async_pager(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='abc', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[], - next_page_token='def', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='ghi', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_delivery_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, delivery_vehicles.DeliveryVehicle) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_delivery_vehicles_async_pages(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='abc', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[], - next_page_token='def', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='ghi', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - ), - 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_delivery_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", [ - delivery_api.CreateDeliveryVehicleRequest, - dict, -]) -def test_create_delivery_vehicle_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request_init["delivery_vehicle"] = {'name': 'name_value', 'last_location': {'location': {'latitude': 0.86, 'longitude': 0.971}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {'value': 541}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {'seconds': 751, 'nanos': 543}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'navigation_status': 1, 'current_route_segment': b'current_route_segment_blob', 'current_route_segment_end_point': {}, 'remaining_distance_meters': {}, 'remaining_duration': {'seconds': 751, 'nanos': 543}, 'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {'point': {}}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {'start_time': {}, 'end_time': {}}}], 'state': 1}, 'driving_distance_meters': {}, 'driving_duration': {}, 'path': {}}], 'attributes': [{'key': 'key_value', 'value': 'value_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}], 'type_': 1} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = delivery_api.CreateDeliveryVehicleRequest.meta.fields["delivery_vehicle"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["delivery_vehicle"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["delivery_vehicle"][field])): - del request_init["delivery_vehicle"][field][i][subfield] - else: - del request_init["delivery_vehicle"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_delivery_vehicle(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - -def test_create_delivery_vehicle_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_delivery_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_delivery_vehicle] = mock_rpc - - request = {} - client.create_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_delivery_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 - - -def test_create_delivery_vehicle_rest_required_fields(request_type=delivery_api.CreateDeliveryVehicleRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["delivery_vehicle_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "deliveryVehicleId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_delivery_vehicle._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "deliveryVehicleId" in jsonified_request - assert jsonified_request["deliveryVehicleId"] == request_init["delivery_vehicle_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["deliveryVehicleId"] = 'delivery_vehicle_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_delivery_vehicle._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("delivery_vehicle_id", "header", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "deliveryVehicleId" in jsonified_request - assert jsonified_request["deliveryVehicleId"] == 'delivery_vehicle_id_value' - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_delivery_vehicle(request) - - expected_params = [ - ( - "deliveryVehicleId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_delivery_vehicle_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_delivery_vehicle._get_unset_required_fields({}) - assert set(unset_fields) == (set(("deliveryVehicleId", "header", )) & set(("parent", "deliveryVehicleId", "deliveryVehicle", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_delivery_vehicle_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_create_delivery_vehicle") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_create_delivery_vehicle") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.CreateDeliveryVehicleRequest.pb(delivery_api.CreateDeliveryVehicleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = delivery_vehicles.DeliveryVehicle.to_json(delivery_vehicles.DeliveryVehicle()) - - request = delivery_api.CreateDeliveryVehicleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_vehicles.DeliveryVehicle() - - client.create_delivery_vehicle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_delivery_vehicle_rest_bad_request(transport: str = 'rest', request_type=delivery_api.CreateDeliveryVehicleRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_delivery_vehicle(request) - - -def test_create_delivery_vehicle_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'providers/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_delivery_vehicle(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=providers/*}/deliveryVehicles" % client.transport._host, args[1]) - - -def test_create_delivery_vehicle_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_delivery_vehicle( - delivery_api.CreateDeliveryVehicleRequest(), - parent='parent_value', - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - -def test_create_delivery_vehicle_rest_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.GetDeliveryVehicleRequest, - dict, -]) -def test_get_delivery_vehicle_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/deliveryVehicles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_delivery_vehicle(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - -def test_get_delivery_vehicle_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_delivery_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_delivery_vehicle] = mock_rpc - - request = {} - client.get_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_delivery_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 - - -def test_get_delivery_vehicle_rest_required_fields(request_type=delivery_api.GetDeliveryVehicleRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_delivery_vehicle._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_delivery_vehicle._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_delivery_vehicle(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_delivery_vehicle_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_delivery_vehicle._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_delivery_vehicle_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_get_delivery_vehicle") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_get_delivery_vehicle") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.GetDeliveryVehicleRequest.pb(delivery_api.GetDeliveryVehicleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = delivery_vehicles.DeliveryVehicle.to_json(delivery_vehicles.DeliveryVehicle()) - - request = delivery_api.GetDeliveryVehicleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_vehicles.DeliveryVehicle() - - client.get_delivery_vehicle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_delivery_vehicle_rest_bad_request(transport: str = 'rest', request_type=delivery_api.GetDeliveryVehicleRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/deliveryVehicles/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_delivery_vehicle(request) - - -def test_get_delivery_vehicle_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'providers/sample1/deliveryVehicles/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_delivery_vehicle(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=providers/*/deliveryVehicles/*}" % client.transport._host, args[1]) - - -def test_get_delivery_vehicle_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_delivery_vehicle( - delivery_api.GetDeliveryVehicleRequest(), - name='name_value', - ) - - -def test_get_delivery_vehicle_rest_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.UpdateDeliveryVehicleRequest, - dict, -]) -def test_update_delivery_vehicle_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'delivery_vehicle': {'name': 'providers/sample1/deliveryVehicles/sample2'}} - request_init["delivery_vehicle"] = {'name': 'providers/sample1/deliveryVehicles/sample2', 'last_location': {'location': {'latitude': 0.86, 'longitude': 0.971}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {'value': 541}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {'seconds': 751, 'nanos': 543}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'navigation_status': 1, 'current_route_segment': b'current_route_segment_blob', 'current_route_segment_end_point': {}, 'remaining_distance_meters': {}, 'remaining_duration': {'seconds': 751, 'nanos': 543}, 'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {'point': {}}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {'start_time': {}, 'end_time': {}}}], 'state': 1}, 'driving_distance_meters': {}, 'driving_duration': {}, 'path': {}}], 'attributes': [{'key': 'key_value', 'value': 'value_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}], 'type_': 1} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = delivery_api.UpdateDeliveryVehicleRequest.meta.fields["delivery_vehicle"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["delivery_vehicle"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["delivery_vehicle"][field])): - del request_init["delivery_vehicle"][field][i][subfield] - else: - del request_init["delivery_vehicle"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle( - name='name_value', - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b'current_route_segment_blob', - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_delivery_vehicle(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == 'name_value' - assert response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - assert response.current_route_segment == b'current_route_segment_blob' - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - -def test_update_delivery_vehicle_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_delivery_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_delivery_vehicle] = mock_rpc - - request = {} - client.update_delivery_vehicle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_delivery_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 - - -def test_update_delivery_vehicle_rest_required_fields(request_type=delivery_api.UpdateDeliveryVehicleRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_delivery_vehicle._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_delivery_vehicle._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_delivery_vehicle(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_delivery_vehicle_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_delivery_vehicle._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", "updateMask", )) & set(("deliveryVehicle", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_delivery_vehicle_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_update_delivery_vehicle") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_update_delivery_vehicle") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.UpdateDeliveryVehicleRequest.pb(delivery_api.UpdateDeliveryVehicleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = delivery_vehicles.DeliveryVehicle.to_json(delivery_vehicles.DeliveryVehicle()) - - request = delivery_api.UpdateDeliveryVehicleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_vehicles.DeliveryVehicle() - - client.update_delivery_vehicle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_delivery_vehicle_rest_bad_request(transport: str = 'rest', request_type=delivery_api.UpdateDeliveryVehicleRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'delivery_vehicle': {'name': 'providers/sample1/deliveryVehicles/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_delivery_vehicle(request) - - -def test_update_delivery_vehicle_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - - # get arguments that satisfy an http rule for this method - sample_request = {'delivery_vehicle': {'name': 'providers/sample1/deliveryVehicles/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_delivery_vehicle(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{delivery_vehicle.name=providers/*/deliveryVehicles/*}" % client.transport._host, args[1]) - - -def test_update_delivery_vehicle_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_delivery_vehicle( - delivery_api.UpdateDeliveryVehicleRequest(), - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_delivery_vehicle_rest_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.BatchCreateTasksRequest, - dict, -]) -def test_batch_create_tasks_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_api.BatchCreateTasksResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_api.BatchCreateTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_create_tasks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_api.BatchCreateTasksResponse) - -def test_batch_create_tasks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.batch_create_tasks 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.batch_create_tasks] = mock_rpc - - request = {} - client.batch_create_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_create_tasks(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_batch_create_tasks_rest_required_fields(request_type=delivery_api.BatchCreateTasksRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_tasks._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_tasks._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_api.BatchCreateTasksResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_api.BatchCreateTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_create_tasks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_create_tasks_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_create_tasks._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_tasks_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_batch_create_tasks") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_batch_create_tasks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.BatchCreateTasksRequest.pb(delivery_api.BatchCreateTasksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = delivery_api.BatchCreateTasksResponse.to_json(delivery_api.BatchCreateTasksResponse()) - - request = delivery_api.BatchCreateTasksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_api.BatchCreateTasksResponse() - - client.batch_create_tasks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_tasks_rest_bad_request(transport: str = 'rest', request_type=delivery_api.BatchCreateTasksRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_create_tasks(request) - - -def test_batch_create_tasks_rest_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.CreateTaskRequest, - dict, -]) -def test_create_task_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request_init["task"] = {'name': 'name_value', 'type_': 1, 'state': 1, 'task_outcome': 1, 'task_outcome_time': {'seconds': 751, 'nanos': 543}, 'task_outcome_location': {'point': {'latitude': 0.86, 'longitude': 0.971}}, 'task_outcome_location_source': 2, 'tracking_id': 'tracking_id_value', 'delivery_vehicle_id': 'delivery_vehicle_id_value', 'planned_location': {}, 'task_duration': {'seconds': 751, 'nanos': 543}, 'target_time_window': {'start_time': {}, 'end_time': {}}, 'journey_sharing_info': {'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {}}], 'state': 1}, 'driving_distance_meters': {'value': 541}, 'driving_duration': {}, 'path': {}}], 'last_location': {'location': {}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'last_location_snappable': True}, 'task_tracking_view_config': {'route_polyline_points_visibility': {'remaining_stop_count_threshold': 3219, 'duration_until_estimated_arrival_time_threshold': {}, 'remaining_driving_distance_meters_threshold': 4561, 'always': True, 'never': True}, 'estimated_arrival_time_visibility': {}, 'estimated_task_completion_time_visibility': {}, 'remaining_driving_distance_visibility': {}, 'remaining_stop_count_visibility': {}, 'vehicle_location_visibility': {}}, 'attributes': [{'key': 'key_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = delivery_api.CreateTaskRequest.meta.fields["task"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["task"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["task"][field])): - del request_init["task"][field][i][subfield] - else: - del request_init["task"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_task(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - -def test_create_task_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_task 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_task] = mock_rpc - - request = {} - client.create_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_task(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_task_rest_required_fields(request_type=delivery_api.CreateTaskRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["task_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "taskId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_task._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "taskId" in jsonified_request - assert jsonified_request["taskId"] == request_init["task_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["taskId"] = 'task_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_task._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", "task_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "taskId" in jsonified_request - assert jsonified_request["taskId"] == 'task_id_value' - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_task(request) - - expected_params = [ - ( - "taskId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_task_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_task._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", "taskId", )) & set(("parent", "taskId", "task", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_task_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_create_task") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_create_task") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.CreateTaskRequest.pb(delivery_api.CreateTaskRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tasks.Task.to_json(tasks.Task()) - - request = delivery_api.CreateTaskRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tasks.Task() - - client.create_task(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_task_rest_bad_request(transport: str = 'rest', request_type=delivery_api.CreateTaskRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_task(request) - - -def test_create_task_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'providers/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_task(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=providers/*}/tasks" % client.transport._host, args[1]) - - -def test_create_task_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_task( - delivery_api.CreateTaskRequest(), - parent='parent_value', - task=tasks.Task(name='name_value'), - task_id='task_id_value', - ) - - -def test_create_task_rest_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.GetTaskRequest, - dict, -]) -def test_get_task_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/tasks/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_task(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - -def test_get_task_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_task 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_task] = mock_rpc - - request = {} - client.get_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_task(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_task_rest_required_fields(request_type=delivery_api.GetTaskRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_task._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_task._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_task(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_task_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_task._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_task_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_get_task") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_get_task") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.GetTaskRequest.pb(delivery_api.GetTaskRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tasks.Task.to_json(tasks.Task()) - - request = delivery_api.GetTaskRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tasks.Task() - - client.get_task(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_task_rest_bad_request(transport: str = 'rest', request_type=delivery_api.GetTaskRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/tasks/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_task(request) - - -def test_get_task_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'providers/sample1/tasks/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_task(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=providers/*/tasks/*}" % client.transport._host, args[1]) - - -def test_get_task_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_task( - delivery_api.GetTaskRequest(), - name='name_value', - ) - - -def test_get_task_rest_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.UpdateTaskRequest, - dict, -]) -def test_update_task_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'task': {'name': 'providers/sample1/tasks/sample2'}} - request_init["task"] = {'name': 'providers/sample1/tasks/sample2', 'type_': 1, 'state': 1, 'task_outcome': 1, 'task_outcome_time': {'seconds': 751, 'nanos': 543}, 'task_outcome_location': {'point': {'latitude': 0.86, 'longitude': 0.971}}, 'task_outcome_location_source': 2, 'tracking_id': 'tracking_id_value', 'delivery_vehicle_id': 'delivery_vehicle_id_value', 'planned_location': {}, 'task_duration': {'seconds': 751, 'nanos': 543}, 'target_time_window': {'start_time': {}, 'end_time': {}}, 'journey_sharing_info': {'remaining_vehicle_journey_segments': [{'stop': {'planned_location': {}, 'tasks': [{'task_id': 'task_id_value', 'task_duration': {}, 'target_time_window': {}}], 'state': 1}, 'driving_distance_meters': {'value': 541}, 'driving_duration': {}, 'path': {}}], 'last_location': {'location': {}, 'horizontal_accuracy': {'value': 0.541}, 'latlng_accuracy': {}, 'heading': {}, 'bearing_accuracy': {}, 'heading_accuracy': {}, 'altitude': {}, 'vertical_accuracy': {}, 'altitude_accuracy': {}, 'speed_kmph': {}, 'speed': {}, 'speed_accuracy': {}, 'update_time': {}, 'server_time': {}, 'location_sensor': 1, 'is_road_snapped': {'value': True}, 'is_gps_sensor_enabled': {}, 'time_since_update': {}, 'num_stale_updates': {}, 'raw_location': {}, 'raw_location_time': {}, 'raw_location_sensor': 1, 'raw_location_accuracy': {}, 'supplemental_location': {}, 'supplemental_location_time': {}, 'supplemental_location_sensor': 1, 'supplemental_location_accuracy': {}, 'road_snapped': True}, 'last_location_snappable': True}, 'task_tracking_view_config': {'route_polyline_points_visibility': {'remaining_stop_count_threshold': 3219, 'duration_until_estimated_arrival_time_threshold': {}, 'remaining_driving_distance_meters_threshold': 4561, 'always': True, 'never': True}, 'estimated_arrival_time_visibility': {}, 'estimated_task_completion_time_visibility': {}, 'remaining_driving_distance_visibility': {}, 'remaining_stop_count_visibility': {}, 'vehicle_location_visibility': {}}, 'attributes': [{'key': 'key_value', 'string_value': 'string_value_value', 'bool_value': True, 'number_value': 0.1285}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = delivery_api.UpdateTaskRequest.meta.fields["task"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["task"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["task"][field])): - del request_init["task"][field][i][subfield] - else: - del request_init["task"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tasks.Task( - name='name_value', - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id='tracking_id_value', - delivery_vehicle_id='delivery_vehicle_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_task(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == 'name_value' - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert response.task_outcome_location_source == tasks.Task.TaskOutcomeLocationSource.PROVIDER - assert response.tracking_id == 'tracking_id_value' - assert response.delivery_vehicle_id == 'delivery_vehicle_id_value' - -def test_update_task_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_task 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_task] = mock_rpc - - request = {} - client.update_task(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_task(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_task_rest_required_fields(request_type=delivery_api.UpdateTaskRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_task._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_task._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_task(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_task_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_task._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", "updateMask", )) & set(("task", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_task_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_update_task") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_update_task") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.UpdateTaskRequest.pb(delivery_api.UpdateTaskRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = tasks.Task.to_json(tasks.Task()) - - request = delivery_api.UpdateTaskRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = tasks.Task() - - client.update_task(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_task_rest_bad_request(transport: str = 'rest', request_type=delivery_api.UpdateTaskRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'task': {'name': 'providers/sample1/tasks/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_task(request) - - -def test_update_task_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = tasks.Task() - - # get arguments that satisfy an http rule for this method - sample_request = {'task': {'name': 'providers/sample1/tasks/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - task=tasks.Task(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_task(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{task.name=providers/*/tasks/*}" % client.transport._host, args[1]) - - -def test_update_task_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_task( - delivery_api.UpdateTaskRequest(), - task=tasks.Task(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_task_rest_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.ListTasksRequest, - dict, -]) -def test_list_tasks_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_api.ListTasksResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_api.ListTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_tasks(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_tasks_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_tasks 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_tasks] = mock_rpc - - request = {} - client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_tasks(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_tasks_rest_required_fields(request_type=delivery_api.ListTasksRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tasks._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_tasks._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "header", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_api.ListTasksResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_api.ListTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_tasks(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_tasks_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_tasks._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "header", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_tasks_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_list_tasks") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_list_tasks") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.ListTasksRequest.pb(delivery_api.ListTasksRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = delivery_api.ListTasksResponse.to_json(delivery_api.ListTasksResponse()) - - request = delivery_api.ListTasksRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_api.ListTasksResponse() - - client.list_tasks(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_tasks_rest_bad_request(transport: str = 'rest', request_type=delivery_api.ListTasksRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_tasks(request) - - -def test_list_tasks_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_api.ListTasksResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'providers/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_api.ListTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_tasks(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=providers/*}/tasks" % client.transport._host, args[1]) - - -def test_list_tasks_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_tasks( - delivery_api.ListTasksRequest(), - parent='parent_value', - ) - - -def test_list_tasks_rest_pager(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token='abc', - ), - delivery_api.ListTasksResponse( - tasks=[], - next_page_token='def', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token='ghi', - ), - delivery_api.ListTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(delivery_api.ListTasksResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'providers/sample1'} - - pager = client.list_tasks(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tasks.Task) - for i in results) - - pages = list(client.list_tasks(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - delivery_api.GetTaskTrackingInfoRequest, - dict, -]) -def test_get_task_tracking_info_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/taskTrackingInfo/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = task_tracking_info.TaskTrackingInfo( - name='name_value', - tracking_id='tracking_id_value', - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = task_tracking_info.TaskTrackingInfo.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_task_tracking_info(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, task_tracking_info.TaskTrackingInfo) - assert response.name == 'name_value' - assert response.tracking_id == 'tracking_id_value' - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - -def test_get_task_tracking_info_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_task_tracking_info 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_task_tracking_info] = mock_rpc - - request = {} - client.get_task_tracking_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_task_tracking_info(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_task_tracking_info_rest_required_fields(request_type=delivery_api.GetTaskTrackingInfoRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_task_tracking_info._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_task_tracking_info._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = task_tracking_info.TaskTrackingInfo() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = task_tracking_info.TaskTrackingInfo.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_task_tracking_info(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_task_tracking_info_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_task_tracking_info._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_task_tracking_info_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_get_task_tracking_info") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_get_task_tracking_info") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.GetTaskTrackingInfoRequest.pb(delivery_api.GetTaskTrackingInfoRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = task_tracking_info.TaskTrackingInfo.to_json(task_tracking_info.TaskTrackingInfo()) - - request = delivery_api.GetTaskTrackingInfoRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = task_tracking_info.TaskTrackingInfo() - - client.get_task_tracking_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_task_tracking_info_rest_bad_request(transport: str = 'rest', request_type=delivery_api.GetTaskTrackingInfoRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'providers/sample1/taskTrackingInfo/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_task_tracking_info(request) - - -def test_get_task_tracking_info_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = task_tracking_info.TaskTrackingInfo() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'providers/sample1/taskTrackingInfo/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = task_tracking_info.TaskTrackingInfo.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_task_tracking_info(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=providers/*/taskTrackingInfo/*}" % client.transport._host, args[1]) - - -def test_get_task_tracking_info_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_task_tracking_info( - delivery_api.GetTaskTrackingInfoRequest(), - name='name_value', - ) - - -def test_get_task_tracking_info_rest_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - delivery_api.ListDeliveryVehiclesRequest, - dict, -]) -def test_list_delivery_vehicles_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_api.ListDeliveryVehiclesResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_api.ListDeliveryVehiclesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_delivery_vehicles(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeliveryVehiclesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - -def test_list_delivery_vehicles_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_delivery_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_delivery_vehicles] = mock_rpc - - request = {} - client.list_delivery_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_delivery_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 - - -def test_list_delivery_vehicles_rest_required_fields(request_type=delivery_api.ListDeliveryVehiclesRequest): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_delivery_vehicles._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_delivery_vehicles._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "header", "page_size", "page_token", "viewport", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_api.ListDeliveryVehiclesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = delivery_api.ListDeliveryVehiclesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_delivery_vehicles(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_delivery_vehicles_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_delivery_vehicles._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "header", "pageSize", "pageToken", "viewport", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_delivery_vehicles_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "post_list_delivery_vehicles") as post, \ - mock.patch.object(transports.DeliveryServiceRestInterceptor, "pre_list_delivery_vehicles") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.ListDeliveryVehiclesRequest.pb(delivery_api.ListDeliveryVehiclesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = delivery_api.ListDeliveryVehiclesResponse.to_json(delivery_api.ListDeliveryVehiclesResponse()) - - request = delivery_api.ListDeliveryVehiclesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_api.ListDeliveryVehiclesResponse() - - client.list_delivery_vehicles(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_delivery_vehicles_rest_bad_request(transport: str = 'rest', request_type=delivery_api.ListDeliveryVehiclesRequest): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'providers/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_delivery_vehicles(request) - - -def test_list_delivery_vehicles_rest_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = delivery_api.ListDeliveryVehiclesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'providers/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_api.ListDeliveryVehiclesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_delivery_vehicles(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=providers/*}/deliveryVehicles" % client.transport._host, args[1]) - - -def test_list_delivery_vehicles_rest_flattened_error(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_delivery_vehicles( - delivery_api.ListDeliveryVehiclesRequest(), - parent='parent_value', - ) - - -def test_list_delivery_vehicles_rest_pager(transport: str = 'rest'): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='abc', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[], - next_page_token='def', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token='ghi', - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(delivery_api.ListDeliveryVehiclesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'providers/sample1'} - - pager = client.list_delivery_vehicles(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, delivery_vehicles.DeliveryVehicle) - for i in results) - - pages = list(client.list_delivery_vehicles(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DeliveryServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DeliveryServiceClient( - 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 = DeliveryServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DeliveryServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DeliveryServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DeliveryServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DeliveryServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DeliveryServiceGrpcTransport, - transports.DeliveryServiceGrpcAsyncIOTransport, - transports.DeliveryServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DeliveryServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DeliveryServiceGrpcTransport, - ) - -def test_delivery_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DeliveryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_delivery_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.fleetengine_delivery_v1.services.delivery_service.transports.DeliveryServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DeliveryServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_delivery_vehicle', - 'get_delivery_vehicle', - 'update_delivery_vehicle', - 'batch_create_tasks', - 'create_task', - 'get_task', - 'update_task', - 'list_tasks', - 'get_task_tracking_info', - 'list_delivery_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_delivery_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_delivery_v1.services.delivery_service.transports.DeliveryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DeliveryServiceTransport( - 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_delivery_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_delivery_v1.services.delivery_service.transports.DeliveryServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DeliveryServiceTransport() - adc.assert_called_once() - - -def test_delivery_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) - DeliveryServiceClient() - 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.DeliveryServiceGrpcTransport, - transports.DeliveryServiceGrpcAsyncIOTransport, - ], -) -def test_delivery_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.DeliveryServiceGrpcTransport, - transports.DeliveryServiceGrpcAsyncIOTransport, - transports.DeliveryServiceRestTransport, - ], -) -def test_delivery_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.DeliveryServiceGrpcTransport, grpc_helpers), - (transports.DeliveryServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_delivery_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.DeliveryServiceGrpcTransport, transports.DeliveryServiceGrpcAsyncIOTransport]) -def test_delivery_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 - ) - -def test_delivery_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.DeliveryServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_delivery_service_host_no_port(transport_name): - client = DeliveryServiceClient( - 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' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://fleetengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_delivery_service_host_with_port(transport_name): - client = DeliveryServiceClient( - 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' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://fleetengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_delivery_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DeliveryServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DeliveryServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_delivery_vehicle._session - session2 = client2.transport.create_delivery_vehicle._session - assert session1 != session2 - session1 = client1.transport.get_delivery_vehicle._session - session2 = client2.transport.get_delivery_vehicle._session - assert session1 != session2 - session1 = client1.transport.update_delivery_vehicle._session - session2 = client2.transport.update_delivery_vehicle._session - assert session1 != session2 - session1 = client1.transport.batch_create_tasks._session - session2 = client2.transport.batch_create_tasks._session - assert session1 != session2 - session1 = client1.transport.create_task._session - session2 = client2.transport.create_task._session - assert session1 != session2 - session1 = client1.transport.get_task._session - session2 = client2.transport.get_task._session - assert session1 != session2 - session1 = client1.transport.update_task._session - session2 = client2.transport.update_task._session - assert session1 != session2 - session1 = client1.transport.list_tasks._session - session2 = client2.transport.list_tasks._session - assert session1 != session2 - session1 = client1.transport.get_task_tracking_info._session - session2 = client2.transport.get_task_tracking_info._session - assert session1 != session2 - session1 = client1.transport.list_delivery_vehicles._session - session2 = client2.transport.list_delivery_vehicles._session - assert session1 != session2 -def test_delivery_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DeliveryServiceGrpcTransport( - 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_delivery_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DeliveryServiceGrpcAsyncIOTransport( - 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.DeliveryServiceGrpcTransport, transports.DeliveryServiceGrpcAsyncIOTransport]) -def test_delivery_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.DeliveryServiceGrpcTransport, transports.DeliveryServiceGrpcAsyncIOTransport]) -def test_delivery_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_delivery_vehicle_path(): - provider = "squid" - vehicle = "clam" - expected = "providers/{provider}/deliveryVehicles/{vehicle}".format(provider=provider, vehicle=vehicle, ) - actual = DeliveryServiceClient.delivery_vehicle_path(provider, vehicle) - assert expected == actual - - -def test_parse_delivery_vehicle_path(): - expected = { - "provider": "whelk", - "vehicle": "octopus", - } - path = DeliveryServiceClient.delivery_vehicle_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_delivery_vehicle_path(path) - assert expected == actual - -def test_task_path(): - provider = "oyster" - task = "nudibranch" - expected = "providers/{provider}/tasks/{task}".format(provider=provider, task=task, ) - actual = DeliveryServiceClient.task_path(provider, task) - assert expected == actual - - -def test_parse_task_path(): - expected = { - "provider": "cuttlefish", - "task": "mussel", - } - path = DeliveryServiceClient.task_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_task_path(path) - assert expected == actual - -def test_task_tracking_info_path(): - provider = "winkle" - tracking = "nautilus" - expected = "providers/{provider}/taskTrackingInfo/{tracking}".format(provider=provider, tracking=tracking, ) - actual = DeliveryServiceClient.task_tracking_info_path(provider, tracking) - assert expected == actual - - -def test_parse_task_tracking_info_path(): - expected = { - "provider": "scallop", - "tracking": "abalone", - } - path = DeliveryServiceClient.task_tracking_info_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_task_tracking_info_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DeliveryServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = DeliveryServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = DeliveryServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = DeliveryServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DeliveryServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = DeliveryServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = DeliveryServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = DeliveryServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DeliveryServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = DeliveryServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DeliveryServiceClient.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.DeliveryServiceTransport, '_prep_wrapped_messages') as prep: - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DeliveryServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DeliveryServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DeliveryServiceClient( - 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", [ - (DeliveryServiceClient, transports.DeliveryServiceGrpcTransport), - (DeliveryServiceAsyncClient, transports.DeliveryServiceGrpcAsyncIOTransport), -]) -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-delivery/google/maps/fleetengine_delivery_v1/types/delivery_api.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/types/delivery_api.py index a8e773aae506..cd619910ac96 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/types/delivery_api.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/types/delivery_api.py @@ -509,7 +509,7 @@ class ListTasksRequest(proto.Message): don't specify a value, or if you filter on an empty string, then all Tasks are returned. For information about the Task properties that you can filter on, see `List - tasks `__. + tasks `__. """ header: mfd_header.DeliveryRequestHeader = proto.Field(