From 8b45c71e906625a39c3b6b682293f7045f591146 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 29 Jan 2025 02:01:28 +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 --- .../google-maps-places/v1/.coveragerc | 13 - owl-bot-staging/google-maps-places/v1/.flake8 | 33 - .../google-maps-places/v1/MANIFEST.in | 2 - .../google-maps-places/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../google-maps-places/v1/docs/conf.py | 376 -- .../google-maps-places/v1/docs/index.rst | 7 - .../v1/docs/places_v1/places.rst | 6 - .../v1/docs/places_v1/services_.rst | 6 - .../v1/docs/places_v1/types_.rst | 6 - .../v1/google/maps/places/__init__.py | 83 - .../v1/google/maps/places/gapic_version.py | 16 - .../v1/google/maps/places/py.typed | 2 - .../v1/google/maps/places_v1/__init__.py | 84 - .../google/maps/places_v1/gapic_metadata.json | 103 - .../v1/google/maps/places_v1/gapic_version.py | 16 - .../v1/google/maps/places_v1/py.typed | 2 - .../maps/places_v1/services/__init__.py | 15 - .../places_v1/services/places/__init__.py | 22 - .../places_v1/services/places/async_client.py | 724 --- .../maps/places_v1/services/places/client.py | 1085 ---- .../services/places/transports/README.rst | 9 - .../services/places/transports/__init__.py | 38 - .../services/places/transports/base.py | 211 - .../services/places/transports/grpc.py | 457 -- .../places/transports/grpc_asyncio.py | 497 -- .../services/places/transports/rest.py | 946 ---- .../services/places/transports/rest_base.py | 307 -- .../google/maps/places_v1/types/__init__.py | 108 - .../maps/places_v1/types/attribution.py | 65 - .../maps/places_v1/types/content_block.py | 68 - .../places_v1/types/contextual_content.py | 218 - .../maps/places_v1/types/ev_charging.py | 176 - .../maps/places_v1/types/fuel_options.py | 149 - .../google/maps/places_v1/types/geometry.py | 58 - .../v1/google/maps/places_v1/types/photo.py | 69 - .../v1/google/maps/places_v1/types/place.py | 1286 ----- .../maps/places_v1/types/places_service.py | 1340 ----- .../google/maps/places_v1/types/polyline.py | 62 - .../maps/places_v1/types/price_range.py | 59 - .../google/maps/places_v1/types/reference.py | 60 - .../v1/google/maps/places_v1/types/review.py | 94 - .../maps/places_v1/types/route_modifiers.py | 76 - .../places_v1/types/routing_preference.py | 71 - .../maps/places_v1/types/routing_summary.py | 95 - .../maps/places_v1/types/travel_mode.py | 63 - .../google-maps-places/v1/mypy.ini | 3 - .../google-maps-places/v1/noxfile.py | 280 -- ...erated_places_autocomplete_places_async.py | 52 - ...nerated_places_autocomplete_places_sync.py | 52 - ..._generated_places_get_photo_media_async.py | 52 - ...1_generated_places_get_photo_media_sync.py | 52 - ...ces_v1_generated_places_get_place_async.py | 52 - ...aces_v1_generated_places_get_place_sync.py | 52 - ...v1_generated_places_search_nearby_async.py | 55 - ..._v1_generated_places_search_nearby_sync.py | 55 - ...s_v1_generated_places_search_text_async.py | 52 - ...es_v1_generated_places_search_text_sync.py | 52 - ...nippet_metadata_google.maps.places.v1.json | 796 --- .../v1/scripts/fixup_places_v1_keywords.py | 180 - .../google-maps-places/v1/setup.py | 99 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.13.txt | 7 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../google-maps-places/v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../v1/tests/unit/gapic/places_v1/__init__.py | 16 - .../tests/unit/gapic/places_v1/test_places.py | 4471 ----------------- .../google/maps/places/gapic_version.py | 2 +- .../google/maps/places_v1/gapic_version.py | 2 +- .../services/places/transports/base.py | 2 +- ...nippet_metadata_google.maps.places.v1.json | 2 +- .../tests/unit/gapic/places_v1/test_places.py | 10 +- 78 files changed, 9 insertions(+), 15716 deletions(-) delete mode 100644 owl-bot-staging/google-maps-places/v1/.coveragerc delete mode 100644 owl-bot-staging/google-maps-places/v1/.flake8 delete mode 100644 owl-bot-staging/google-maps-places/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-maps-places/v1/README.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places/py.typed delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/py.typed delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py delete mode 100644 owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py delete mode 100644 owl-bot-staging/google-maps-places/v1/mypy.ini delete mode 100644 owl-bot-staging/google-maps-places/v1/noxfile.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_async.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_sync.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_async.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_sync.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_async.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_sync.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_async.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_sync.py delete mode 100644 owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json delete mode 100644 owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py delete mode 100644 owl-bot-staging/google-maps-places/v1/setup.py delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-maps-places/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/__init__.py delete mode 100644 owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/test_places.py diff --git a/owl-bot-staging/google-maps-places/v1/.coveragerc b/owl-bot-staging/google-maps-places/v1/.coveragerc deleted file mode 100644 index 85cb2db49afb..000000000000 --- a/owl-bot-staging/google-maps-places/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/maps/places/__init__.py - google/maps/places/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-places/v1/.flake8 b/owl-bot-staging/google-maps-places/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/MANIFEST.in b/owl-bot-staging/google-maps-places/v1/MANIFEST.in deleted file mode 100644 index aca0ee5357fb..000000000000 --- a/owl-bot-staging/google-maps-places/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/maps/places *.py -recursive-include google/maps/places_v1 *.py diff --git a/owl-bot-staging/google-maps-places/v1/README.rst b/owl-bot-staging/google-maps-places/v1/README.rst deleted file mode 100644 index a4719af79336..000000000000 --- a/owl-bot-staging/google-maps-places/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Maps Places 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 Places 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-places/v1/docs/_static/custom.css b/owl-bot-staging/google-maps-places/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/docs/conf.py b/owl-bot-staging/google-maps-places/v1/docs/conf.py deleted file mode 100644 index db77e54d8b8d..000000000000 --- a/owl-bot-staging/google-maps-places/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-places 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-places" -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-places-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-places.tex", - u"google-maps-places 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-places", - u"Google Maps Places 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-places", - u"google-maps-places Documentation", - author, - "google-maps-places", - "GAPIC library for Google Maps Places 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-places/v1/docs/index.rst b/owl-bot-staging/google-maps-places/v1/docs/index.rst deleted file mode 100644 index bb4fadc1e6f8..000000000000 --- a/owl-bot-staging/google-maps-places/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - places_v1/services_ - places_v1/types_ diff --git a/owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst b/owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst deleted file mode 100644 index cf160d2126f2..000000000000 --- a/owl-bot-staging/google-maps-places/v1/docs/places_v1/places.rst +++ /dev/null @@ -1,6 +0,0 @@ -Places ------------------------- - -.. automodule:: google.maps.places_v1.services.places - :members: - :inherited-members: diff --git a/owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst b/owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst deleted file mode 100644 index 91337ff78a9a..000000000000 --- a/owl-bot-staging/google-maps-places/v1/docs/places_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Maps Places v1 API -====================================== -.. toctree:: - :maxdepth: 2 - - places diff --git a/owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst b/owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst deleted file mode 100644 index d634d52d3f87..000000000000 --- a/owl-bot-staging/google-maps-places/v1/docs/places_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Maps Places v1 API -=================================== - -.. automodule:: google.maps.places_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py deleted file mode 100644 index b6e255b38d0f..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places/__init__.py +++ /dev/null @@ -1,83 +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.places import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.maps.places_v1.services.places.client import PlacesClient -from google.maps.places_v1.services.places.async_client import PlacesAsyncClient - -from google.maps.places_v1.types.attribution import AuthorAttribution -from google.maps.places_v1.types.content_block import ContentBlock -from google.maps.places_v1.types.contextual_content import ContextualContent -from google.maps.places_v1.types.ev_charging import EVChargeOptions -from google.maps.places_v1.types.ev_charging import EVConnectorType -from google.maps.places_v1.types.fuel_options import FuelOptions -from google.maps.places_v1.types.geometry import Circle -from google.maps.places_v1.types.photo import Photo -from google.maps.places_v1.types.place import Place -from google.maps.places_v1.types.place import PriceLevel -from google.maps.places_v1.types.places_service import AutocompletePlacesRequest -from google.maps.places_v1.types.places_service import AutocompletePlacesResponse -from google.maps.places_v1.types.places_service import GetPhotoMediaRequest -from google.maps.places_v1.types.places_service import GetPlaceRequest -from google.maps.places_v1.types.places_service import PhotoMedia -from google.maps.places_v1.types.places_service import RoutingParameters -from google.maps.places_v1.types.places_service import SearchNearbyRequest -from google.maps.places_v1.types.places_service import SearchNearbyResponse -from google.maps.places_v1.types.places_service import SearchTextRequest -from google.maps.places_v1.types.places_service import SearchTextResponse -from google.maps.places_v1.types.polyline import Polyline -from google.maps.places_v1.types.price_range import PriceRange -from google.maps.places_v1.types.reference import References -from google.maps.places_v1.types.review import Review -from google.maps.places_v1.types.route_modifiers import RouteModifiers -from google.maps.places_v1.types.routing_preference import RoutingPreference -from google.maps.places_v1.types.routing_summary import RoutingSummary -from google.maps.places_v1.types.travel_mode import TravelMode - -__all__ = ('PlacesClient', - 'PlacesAsyncClient', - 'AuthorAttribution', - 'ContentBlock', - 'ContextualContent', - 'EVChargeOptions', - 'EVConnectorType', - 'FuelOptions', - 'Circle', - 'Photo', - 'Place', - 'PriceLevel', - 'AutocompletePlacesRequest', - 'AutocompletePlacesResponse', - 'GetPhotoMediaRequest', - 'GetPlaceRequest', - 'PhotoMedia', - 'RoutingParameters', - 'SearchNearbyRequest', - 'SearchNearbyResponse', - 'SearchTextRequest', - 'SearchTextResponse', - 'Polyline', - 'PriceRange', - 'References', - 'Review', - 'RouteModifiers', - 'RoutingPreference', - 'RoutingSummary', - 'TravelMode', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places/gapic_version.py b/owl-bot-staging/google-maps-places/v1/google/maps/places/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places/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-places/v1/google/maps/places/py.typed b/owl-bot-staging/google-maps-places/v1/google/maps/places/py.typed deleted file mode 100644 index ae821546ded2..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-places package uses inline types. diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__init__.py deleted file mode 100644 index 42c0424e3800..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/__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 google.maps.places_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.places import PlacesClient -from .services.places import PlacesAsyncClient - -from .types.attribution import AuthorAttribution -from .types.content_block import ContentBlock -from .types.contextual_content import ContextualContent -from .types.ev_charging import EVChargeOptions -from .types.ev_charging import EVConnectorType -from .types.fuel_options import FuelOptions -from .types.geometry import Circle -from .types.photo import Photo -from .types.place import Place -from .types.place import PriceLevel -from .types.places_service import AutocompletePlacesRequest -from .types.places_service import AutocompletePlacesResponse -from .types.places_service import GetPhotoMediaRequest -from .types.places_service import GetPlaceRequest -from .types.places_service import PhotoMedia -from .types.places_service import RoutingParameters -from .types.places_service import SearchNearbyRequest -from .types.places_service import SearchNearbyResponse -from .types.places_service import SearchTextRequest -from .types.places_service import SearchTextResponse -from .types.polyline import Polyline -from .types.price_range import PriceRange -from .types.reference import References -from .types.review import Review -from .types.route_modifiers import RouteModifiers -from .types.routing_preference import RoutingPreference -from .types.routing_summary import RoutingSummary -from .types.travel_mode import TravelMode - -__all__ = ( - 'PlacesAsyncClient', -'AuthorAttribution', -'AutocompletePlacesRequest', -'AutocompletePlacesResponse', -'Circle', -'ContentBlock', -'ContextualContent', -'EVChargeOptions', -'EVConnectorType', -'FuelOptions', -'GetPhotoMediaRequest', -'GetPlaceRequest', -'Photo', -'PhotoMedia', -'Place', -'PlacesClient', -'Polyline', -'PriceLevel', -'PriceRange', -'References', -'Review', -'RouteModifiers', -'RoutingParameters', -'RoutingPreference', -'RoutingSummary', -'SearchNearbyRequest', -'SearchNearbyResponse', -'SearchTextRequest', -'SearchTextResponse', -'TravelMode', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json deleted file mode 100644 index 00da5ef96769..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_metadata.json +++ /dev/null @@ -1,103 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.maps.places_v1", - "protoPackage": "google.maps.places.v1", - "schema": "1.0", - "services": { - "Places": { - "clients": { - "grpc": { - "libraryClient": "PlacesClient", - "rpcs": { - "AutocompletePlaces": { - "methods": [ - "autocomplete_places" - ] - }, - "GetPhotoMedia": { - "methods": [ - "get_photo_media" - ] - }, - "GetPlace": { - "methods": [ - "get_place" - ] - }, - "SearchNearby": { - "methods": [ - "search_nearby" - ] - }, - "SearchText": { - "methods": [ - "search_text" - ] - } - } - }, - "grpc-async": { - "libraryClient": "PlacesAsyncClient", - "rpcs": { - "AutocompletePlaces": { - "methods": [ - "autocomplete_places" - ] - }, - "GetPhotoMedia": { - "methods": [ - "get_photo_media" - ] - }, - "GetPlace": { - "methods": [ - "get_place" - ] - }, - "SearchNearby": { - "methods": [ - "search_nearby" - ] - }, - "SearchText": { - "methods": [ - "search_text" - ] - } - } - }, - "rest": { - "libraryClient": "PlacesClient", - "rpcs": { - "AutocompletePlaces": { - "methods": [ - "autocomplete_places" - ] - }, - "GetPhotoMedia": { - "methods": [ - "get_photo_media" - ] - }, - "GetPlace": { - "methods": [ - "get_place" - ] - }, - "SearchNearby": { - "methods": [ - "search_nearby" - ] - }, - "SearchText": { - "methods": [ - "search_text" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_version.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_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-places/v1/google/maps/places_v1/py.typed b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/py.typed deleted file mode 100644 index ae821546ded2..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-maps-places package uses inline types. diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_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-places/v1/google/maps/places_v1/services/places/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/__init__.py deleted file mode 100644 index 3842d6478d3e..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/__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 PlacesClient -from .async_client import PlacesAsyncClient - -__all__ = ( - 'PlacesClient', - 'PlacesAsyncClient', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py deleted file mode 100644 index 11accc1ee01f..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/async_client.py +++ /dev/null @@ -1,724 +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 logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.maps.places_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.geo.type.types import viewport -from google.maps.places_v1.types import contextual_content -from google.maps.places_v1.types import ev_charging -from google.maps.places_v1.types import fuel_options -from google.maps.places_v1.types import photo -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service -from google.maps.places_v1.types import price_range -from google.maps.places_v1.types import review -from google.maps.places_v1.types import routing_summary -from google.type import latlng_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore -from .transports.base import PlacesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import PlacesGrpcAsyncIOTransport -from .client import PlacesClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class PlacesAsyncClient: - """Service definition for the Places API. Note: every request (except - for Autocomplete requests) requires a field mask set outside of the - request proto (``all/*``, is not assumed). The field mask can be set - via the HTTP header ``X-Goog-FieldMask``. See: - https://developers.google.com/maps/documentation/places/web-service/choose-fields - """ - - _client: PlacesClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = PlacesClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = PlacesClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = PlacesClient._DEFAULT_UNIVERSE - - photo_path = staticmethod(PlacesClient.photo_path) - parse_photo_path = staticmethod(PlacesClient.parse_photo_path) - photo_media_path = staticmethod(PlacesClient.photo_media_path) - parse_photo_media_path = staticmethod(PlacesClient.parse_photo_media_path) - place_path = staticmethod(PlacesClient.place_path) - parse_place_path = staticmethod(PlacesClient.parse_place_path) - review_path = staticmethod(PlacesClient.review_path) - parse_review_path = staticmethod(PlacesClient.parse_review_path) - common_billing_account_path = staticmethod(PlacesClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(PlacesClient.parse_common_billing_account_path) - common_folder_path = staticmethod(PlacesClient.common_folder_path) - parse_common_folder_path = staticmethod(PlacesClient.parse_common_folder_path) - common_organization_path = staticmethod(PlacesClient.common_organization_path) - parse_common_organization_path = staticmethod(PlacesClient.parse_common_organization_path) - common_project_path = staticmethod(PlacesClient.common_project_path) - parse_common_project_path = staticmethod(PlacesClient.parse_common_project_path) - common_location_path = staticmethod(PlacesClient.common_location_path) - parse_common_location_path = staticmethod(PlacesClient.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: - PlacesAsyncClient: The constructed client. - """ - return PlacesClient.from_service_account_info.__func__(PlacesAsyncClient, 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: - PlacesAsyncClient: The constructed client. - """ - return PlacesClient.from_service_account_file.__func__(PlacesAsyncClient, 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 PlacesClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> PlacesTransport: - """Returns the transport used by the client instance. - - Returns: - PlacesTransport: 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 = PlacesClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, PlacesTransport, Callable[..., PlacesTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the places 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,PlacesTransport,Callable[..., PlacesTransport]]]): - 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 PlacesTransport 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 = PlacesClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.maps.places_v1.PlacesAsyncClient`.", - extra = { - "serviceName": "google.maps.places.v1.Places", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.maps.places.v1.Places", - "credentialsType": None, - } - ) - - async def search_nearby(self, - request: Optional[Union[places_service.SearchNearbyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.SearchNearbyResponse: - r"""Search for places near locations. - - .. 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 places_v1 - - async def sample_search_nearby(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - location_restriction = places_v1.LocationRestriction() - location_restriction.circle.radius = 0.648 - - request = places_v1.SearchNearbyRequest( - location_restriction=location_restriction, - ) - - # Make the request - response = await client.search_nearby(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.places_v1.types.SearchNearbyRequest, dict]]): - The request object. Request proto for Search Nearby. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.SearchNearbyResponse: - Response proto for Search Nearby. - """ - # 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, places_service.SearchNearbyRequest): - request = places_service.SearchNearbyRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.search_nearby] - - # 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 search_text(self, - request: Optional[Union[places_service.SearchTextRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.SearchTextResponse: - r"""Text query based place search. - - .. 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 places_v1 - - async def sample_search_text(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.SearchTextRequest( - text_query="text_query_value", - ) - - # Make the request - response = await client.search_text(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.places_v1.types.SearchTextRequest, dict]]): - The request object. Request proto for SearchText. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.SearchTextResponse: - Response proto for SearchText. - """ - # 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, places_service.SearchTextRequest): - request = places_service.SearchTextRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.search_text] - - # 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_photo_media(self, - request: Optional[Union[places_service.GetPhotoMediaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.PhotoMedia: - r"""Get a photo media with a photo reference string. - - .. 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 places_v1 - - async def sample_get_photo_media(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.GetPhotoMediaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_photo_media(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.places_v1.types.GetPhotoMediaRequest, dict]]): - The request object. Request for fetching a photo of a - place using a photo resource name. - name (:class:`str`): - Required. The resource name of a photo media in the - format: - ``places/{place_id}/photos/{photo_reference}/media``. - - The resource name of a photo as returned in a Place - object's ``photos.name`` field comes with the format - ``places/{place_id}/photos/{photo_reference}``. You need - to append ``/media`` at the end of the photo resource to - get the photo media resource name. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.PhotoMedia: - A photo media from Places API. - """ - # 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, places_service.GetPhotoMediaRequest): - request = places_service.GetPhotoMediaRequest(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_photo_media] - - # 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 get_place(self, - request: Optional[Union[places_service.GetPlaceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> place.Place: - r"""Get the details of a place based on its resource name, which is - a string in the ``places/{place_id}`` format. - - .. 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 places_v1 - - async def sample_get_place(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.GetPlaceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_place(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.places_v1.types.GetPlaceRequest, dict]]): - The request object. Request for fetching a Place based on its resource name, - which is a string in the ``places/{place_id}`` format. - name (:class:`str`): - Required. The resource name of a place, in the - ``places/{place_id}`` format. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.Place: - All the information representing a - Place. - - """ - # 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, places_service.GetPlaceRequest): - request = places_service.GetPlaceRequest(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_place] - - # 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 autocomplete_places(self, - request: Optional[Union[places_service.AutocompletePlacesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.AutocompletePlacesResponse: - r"""Returns predictions for the given input. - - .. 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 places_v1 - - async def sample_autocomplete_places(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.AutocompletePlacesRequest( - input="input_value", - ) - - # Make the request - response = await client.autocomplete_places(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.places_v1.types.AutocompletePlacesRequest, dict]]): - The request object. Request proto for AutocompletePlaces. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.AutocompletePlacesResponse: - Response proto for - AutocompletePlaces. - - """ - # 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, places_service.AutocompletePlacesRequest): - request = places_service.AutocompletePlacesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.autocomplete_places] - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "PlacesAsyncClient": - 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__ = ( - "PlacesAsyncClient", -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py deleted file mode 100644 index e5eafbb91b62..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/client.py +++ /dev/null @@ -1,1085 +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 logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.maps.places_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 - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.geo.type.types import viewport -from google.maps.places_v1.types import contextual_content -from google.maps.places_v1.types import ev_charging -from google.maps.places_v1.types import fuel_options -from google.maps.places_v1.types import photo -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service -from google.maps.places_v1.types import price_range -from google.maps.places_v1.types import review -from google.maps.places_v1.types import routing_summary -from google.type import latlng_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore -from .transports.base import PlacesTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import PlacesGrpcTransport -from .transports.grpc_asyncio import PlacesGrpcAsyncIOTransport -from .transports.rest import PlacesRestTransport - - -class PlacesClientMeta(type): - """Metaclass for the Places 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[PlacesTransport]] - _transport_registry["grpc"] = PlacesGrpcTransport - _transport_registry["grpc_asyncio"] = PlacesGrpcAsyncIOTransport - _transport_registry["rest"] = PlacesRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[PlacesTransport]: - """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 PlacesClient(metaclass=PlacesClientMeta): - """Service definition for the Places API. Note: every request (except - for Autocomplete requests) requires a field mask set outside of the - request proto (``all/*``, is not assumed). The field mask can be set - via the HTTP header ``X-Goog-FieldMask``. See: - https://developers.google.com/maps/documentation/places/web-service/choose-fields - """ - - @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 = "places.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "places.{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: - PlacesClient: 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: - PlacesClient: 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) -> PlacesTransport: - """Returns the transport used by the client instance. - - Returns: - PlacesTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def photo_path(place: str,photo: str,) -> str: - """Returns a fully-qualified photo string.""" - return "places/{place}/photos/{photo}".format(place=place, photo=photo, ) - - @staticmethod - def parse_photo_path(path: str) -> Dict[str,str]: - """Parses a photo path into its component segments.""" - m = re.match(r"^places/(?P.+?)/photos/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def photo_media_path(place_id: str,photo_reference: str,) -> str: - """Returns a fully-qualified photo_media string.""" - return "places/{place_id}/photos/{photo_reference}/media".format(place_id=place_id, photo_reference=photo_reference, ) - - @staticmethod - def parse_photo_media_path(path: str) -> Dict[str,str]: - """Parses a photo_media path into its component segments.""" - m = re.match(r"^places/(?P.+?)/photos/(?P.+?)/media$", path) - return m.groupdict() if m else {} - - @staticmethod - def place_path(place_id: str,) -> str: - """Returns a fully-qualified place string.""" - return "places/{place_id}".format(place_id=place_id, ) - - @staticmethod - def parse_place_path(path: str) -> Dict[str,str]: - """Parses a place path into its component segments.""" - m = re.match(r"^places/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def review_path(place: str,review: str,) -> str: - """Returns a fully-qualified review string.""" - return "places/{place}/reviews/{review}".format(place=place, review=review, ) - - @staticmethod - def parse_review_path(path: str) -> Dict[str,str]: - """Parses a review path into its component segments.""" - m = re.match(r"^places/(?P.+?)/reviews/(?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 = PlacesClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = PlacesClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = PlacesClient._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 = PlacesClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, PlacesTransport, Callable[..., PlacesTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the places 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,PlacesTransport,Callable[..., PlacesTransport]]]): - 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 PlacesTransport 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 = PlacesClient._read_environment_variables() - self._client_cert_source = PlacesClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = PlacesClient._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 - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - 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, PlacesTransport) - if transport_provided: - # transport is a PlacesTransport 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(PlacesTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - PlacesClient._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[PlacesTransport], Callable[..., PlacesTransport]] = ( - PlacesClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., PlacesTransport], 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, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.maps.places_v1.PlacesClient`.", - extra = { - "serviceName": "google.maps.places.v1.Places", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.maps.places.v1.Places", - "credentialsType": None, - } - ) - - def search_nearby(self, - request: Optional[Union[places_service.SearchNearbyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.SearchNearbyResponse: - r"""Search for places near locations. - - .. 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 places_v1 - - def sample_search_nearby(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - location_restriction = places_v1.LocationRestriction() - location_restriction.circle.radius = 0.648 - - request = places_v1.SearchNearbyRequest( - location_restriction=location_restriction, - ) - - # Make the request - response = client.search_nearby(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.places_v1.types.SearchNearbyRequest, dict]): - The request object. Request proto for Search Nearby. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.SearchNearbyResponse: - Response proto for Search Nearby. - """ - # 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, places_service.SearchNearbyRequest): - request = places_service.SearchNearbyRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_nearby] - - # 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 search_text(self, - request: Optional[Union[places_service.SearchTextRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.SearchTextResponse: - r"""Text query based place search. - - .. 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 places_v1 - - def sample_search_text(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.SearchTextRequest( - text_query="text_query_value", - ) - - # Make the request - response = client.search_text(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.places_v1.types.SearchTextRequest, dict]): - The request object. Request proto for SearchText. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.SearchTextResponse: - Response proto for SearchText. - """ - # 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, places_service.SearchTextRequest): - request = places_service.SearchTextRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_text] - - # 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_photo_media(self, - request: Optional[Union[places_service.GetPhotoMediaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.PhotoMedia: - r"""Get a photo media with a photo reference string. - - .. 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 places_v1 - - def sample_get_photo_media(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.GetPhotoMediaRequest( - name="name_value", - ) - - # Make the request - response = client.get_photo_media(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.places_v1.types.GetPhotoMediaRequest, dict]): - The request object. Request for fetching a photo of a - place using a photo resource name. - name (str): - Required. The resource name of a photo media in the - format: - ``places/{place_id}/photos/{photo_reference}/media``. - - The resource name of a photo as returned in a Place - object's ``photos.name`` field comes with the format - ``places/{place_id}/photos/{photo_reference}``. You need - to append ``/media`` at the end of the photo resource to - get the photo media resource name. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.PhotoMedia: - A photo media from Places API. - """ - # 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, places_service.GetPhotoMediaRequest): - request = places_service.GetPhotoMediaRequest(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_photo_media] - - # 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._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_place(self, - request: Optional[Union[places_service.GetPlaceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> place.Place: - r"""Get the details of a place based on its resource name, which is - a string in the ``places/{place_id}`` format. - - .. 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 places_v1 - - def sample_get_place(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.GetPlaceRequest( - name="name_value", - ) - - # Make the request - response = client.get_place(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.places_v1.types.GetPlaceRequest, dict]): - The request object. Request for fetching a Place based on its resource name, - which is a string in the ``places/{place_id}`` format. - name (str): - Required. The resource name of a place, in the - ``places/{place_id}`` format. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.Place: - All the information representing a - Place. - - """ - # 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, places_service.GetPlaceRequest): - request = places_service.GetPlaceRequest(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_place] - - # 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._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def autocomplete_places(self, - request: Optional[Union[places_service.AutocompletePlacesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> places_service.AutocompletePlacesResponse: - r"""Returns predictions for the given input. - - .. 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 places_v1 - - def sample_autocomplete_places(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.AutocompletePlacesRequest( - input="input_value", - ) - - # Make the request - response = client.autocomplete_places(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.places_v1.types.AutocompletePlacesRequest, dict]): - The request object. Request proto for AutocompletePlaces. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.maps.places_v1.types.AutocompletePlacesResponse: - Response proto for - AutocompletePlaces. - - """ - # 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, places_service.AutocompletePlacesRequest): - request = places_service.AutocompletePlacesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.autocomplete_places] - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "PlacesClient": - 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__ = ( - "PlacesClient", -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst deleted file mode 100644 index 954b9149d54e..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`PlacesTransport` is the ABC for all transports. -- public child `PlacesGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `PlacesGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BasePlacesRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `PlacesRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/__init__.py deleted file mode 100644 index 6400d3052ce1..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/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 PlacesTransport -from .grpc import PlacesGrpcTransport -from .grpc_asyncio import PlacesGrpcAsyncIOTransport -from .rest import PlacesRestTransport -from .rest import PlacesRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[PlacesTransport]] -_transport_registry['grpc'] = PlacesGrpcTransport -_transport_registry['grpc_asyncio'] = PlacesGrpcAsyncIOTransport -_transport_registry['rest'] = PlacesRestTransport - -__all__ = ( - 'PlacesTransport', - 'PlacesGrpcTransport', - 'PlacesGrpcAsyncIOTransport', - 'PlacesRestTransport', - 'PlacesRestInterceptor', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py deleted file mode 100644 index 5812c25e0ec1..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/base.py +++ /dev/null @@ -1,211 +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.places_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.places_v1.types import place -from google.maps.places_v1.types import places_service - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class PlacesTransport(abc.ABC): - """Abstract transport class for Places.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'places.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: 'places.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.search_nearby: gapic_v1.method.wrap_method( - self.search_nearby, - default_timeout=None, - client_info=client_info, - ), - self.search_text: gapic_v1.method.wrap_method( - self.search_text, - default_timeout=None, - client_info=client_info, - ), - self.get_photo_media: gapic_v1.method.wrap_method( - self.get_photo_media, - default_timeout=None, - client_info=client_info, - ), - self.get_place: gapic_v1.method.wrap_method( - self.get_place, - default_timeout=None, - client_info=client_info, - ), - self.autocomplete_places: gapic_v1.method.wrap_method( - self.autocomplete_places, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def search_nearby(self) -> Callable[ - [places_service.SearchNearbyRequest], - Union[ - places_service.SearchNearbyResponse, - Awaitable[places_service.SearchNearbyResponse] - ]]: - raise NotImplementedError() - - @property - def search_text(self) -> Callable[ - [places_service.SearchTextRequest], - Union[ - places_service.SearchTextResponse, - Awaitable[places_service.SearchTextResponse] - ]]: - raise NotImplementedError() - - @property - def get_photo_media(self) -> Callable[ - [places_service.GetPhotoMediaRequest], - Union[ - places_service.PhotoMedia, - Awaitable[places_service.PhotoMedia] - ]]: - raise NotImplementedError() - - @property - def get_place(self) -> Callable[ - [places_service.GetPlaceRequest], - Union[ - place.Place, - Awaitable[place.Place] - ]]: - raise NotImplementedError() - - @property - def autocomplete_places(self) -> Callable[ - [places_service.AutocompletePlacesRequest], - Union[ - places_service.AutocompletePlacesResponse, - Awaitable[places_service.AutocompletePlacesResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'PlacesTransport', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py deleted file mode 100644 index 84c3a151b6bf..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc.py +++ /dev/null @@ -1,457 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -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 -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service -from .base import PlacesTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": client_call_details.method, - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class PlacesGrpcTransport(PlacesTransport): - """gRPC backend transport for Places. - - Service definition for the Places API. Note: every request (except - for Autocomplete requests) requires a field mask set outside of the - request proto (``all/*``, is not assumed). The field mask can be set - via the HTTP header ``X-Goog-FieldMask``. See: - https://developers.google.com/maps/documentation/places/web-service/choose-fields - - 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 = 'places.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: 'places.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), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'places.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 search_nearby(self) -> Callable[ - [places_service.SearchNearbyRequest], - places_service.SearchNearbyResponse]: - r"""Return a callable for the search nearby method over gRPC. - - Search for places near locations. - - Returns: - Callable[[~.SearchNearbyRequest], - ~.SearchNearbyResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_nearby' not in self._stubs: - self._stubs['search_nearby'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/SearchNearby', - request_serializer=places_service.SearchNearbyRequest.serialize, - response_deserializer=places_service.SearchNearbyResponse.deserialize, - ) - return self._stubs['search_nearby'] - - @property - def search_text(self) -> Callable[ - [places_service.SearchTextRequest], - places_service.SearchTextResponse]: - r"""Return a callable for the search text method over gRPC. - - Text query based place search. - - Returns: - Callable[[~.SearchTextRequest], - ~.SearchTextResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_text' not in self._stubs: - self._stubs['search_text'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/SearchText', - request_serializer=places_service.SearchTextRequest.serialize, - response_deserializer=places_service.SearchTextResponse.deserialize, - ) - return self._stubs['search_text'] - - @property - def get_photo_media(self) -> Callable[ - [places_service.GetPhotoMediaRequest], - places_service.PhotoMedia]: - r"""Return a callable for the get photo media method over gRPC. - - Get a photo media with a photo reference string. - - Returns: - Callable[[~.GetPhotoMediaRequest], - ~.PhotoMedia]: - 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_photo_media' not in self._stubs: - self._stubs['get_photo_media'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/GetPhotoMedia', - request_serializer=places_service.GetPhotoMediaRequest.serialize, - response_deserializer=places_service.PhotoMedia.deserialize, - ) - return self._stubs['get_photo_media'] - - @property - def get_place(self) -> Callable[ - [places_service.GetPlaceRequest], - place.Place]: - r"""Return a callable for the get place method over gRPC. - - Get the details of a place based on its resource name, which is - a string in the ``places/{place_id}`` format. - - Returns: - Callable[[~.GetPlaceRequest], - ~.Place]: - 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_place' not in self._stubs: - self._stubs['get_place'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/GetPlace', - request_serializer=places_service.GetPlaceRequest.serialize, - response_deserializer=place.Place.deserialize, - ) - return self._stubs['get_place'] - - @property - def autocomplete_places(self) -> Callable[ - [places_service.AutocompletePlacesRequest], - places_service.AutocompletePlacesResponse]: - r"""Return a callable for the autocomplete places method over gRPC. - - Returns predictions for the given input. - - Returns: - Callable[[~.AutocompletePlacesRequest], - ~.AutocompletePlacesResponse]: - 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 'autocomplete_places' not in self._stubs: - self._stubs['autocomplete_places'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/AutocompletePlaces', - request_serializer=places_service.AutocompletePlacesRequest.serialize, - response_deserializer=places_service.AutocompletePlacesResponse.deserialize, - ) - return self._stubs['autocomplete_places'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'PlacesGrpcTransport', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py deleted file mode 100644 index f2be3e2b000e..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/grpc_asyncio.py +++ /dev/null @@ -1,497 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -import logging as std_logging -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 -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service -from .base import PlacesTransport, DEFAULT_CLIENT_INFO -from .grpc import PlacesGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class PlacesGrpcAsyncIOTransport(PlacesTransport): - """gRPC AsyncIO backend transport for Places. - - Service definition for the Places API. Note: every request (except - for Autocomplete requests) requires a field mask set outside of the - request proto (``all/*``, is not assumed). The field mask can be set - via the HTTP header ``X-Goog-FieldMask``. See: - https://developers.google.com/maps/documentation/places/web-service/choose-fields - - 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 = 'places.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 = 'places.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: 'places.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), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_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 search_nearby(self) -> Callable[ - [places_service.SearchNearbyRequest], - Awaitable[places_service.SearchNearbyResponse]]: - r"""Return a callable for the search nearby method over gRPC. - - Search for places near locations. - - Returns: - Callable[[~.SearchNearbyRequest], - Awaitable[~.SearchNearbyResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_nearby' not in self._stubs: - self._stubs['search_nearby'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/SearchNearby', - request_serializer=places_service.SearchNearbyRequest.serialize, - response_deserializer=places_service.SearchNearbyResponse.deserialize, - ) - return self._stubs['search_nearby'] - - @property - def search_text(self) -> Callable[ - [places_service.SearchTextRequest], - Awaitable[places_service.SearchTextResponse]]: - r"""Return a callable for the search text method over gRPC. - - Text query based place search. - - Returns: - Callable[[~.SearchTextRequest], - Awaitable[~.SearchTextResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search_text' not in self._stubs: - self._stubs['search_text'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/SearchText', - request_serializer=places_service.SearchTextRequest.serialize, - response_deserializer=places_service.SearchTextResponse.deserialize, - ) - return self._stubs['search_text'] - - @property - def get_photo_media(self) -> Callable[ - [places_service.GetPhotoMediaRequest], - Awaitable[places_service.PhotoMedia]]: - r"""Return a callable for the get photo media method over gRPC. - - Get a photo media with a photo reference string. - - Returns: - Callable[[~.GetPhotoMediaRequest], - Awaitable[~.PhotoMedia]]: - 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_photo_media' not in self._stubs: - self._stubs['get_photo_media'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/GetPhotoMedia', - request_serializer=places_service.GetPhotoMediaRequest.serialize, - response_deserializer=places_service.PhotoMedia.deserialize, - ) - return self._stubs['get_photo_media'] - - @property - def get_place(self) -> Callable[ - [places_service.GetPlaceRequest], - Awaitable[place.Place]]: - r"""Return a callable for the get place method over gRPC. - - Get the details of a place based on its resource name, which is - a string in the ``places/{place_id}`` format. - - Returns: - Callable[[~.GetPlaceRequest], - Awaitable[~.Place]]: - 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_place' not in self._stubs: - self._stubs['get_place'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/GetPlace', - request_serializer=places_service.GetPlaceRequest.serialize, - response_deserializer=place.Place.deserialize, - ) - return self._stubs['get_place'] - - @property - def autocomplete_places(self) -> Callable[ - [places_service.AutocompletePlacesRequest], - Awaitable[places_service.AutocompletePlacesResponse]]: - r"""Return a callable for the autocomplete places method over gRPC. - - Returns predictions for the given input. - - Returns: - Callable[[~.AutocompletePlacesRequest], - Awaitable[~.AutocompletePlacesResponse]]: - 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 'autocomplete_places' not in self._stubs: - self._stubs['autocomplete_places'] = self._logged_channel.unary_unary( - '/google.maps.places.v1.Places/AutocompletePlaces', - request_serializer=places_service.AutocompletePlacesRequest.serialize, - response_deserializer=places_service.AutocompletePlacesResponse.deserialize, - ) - return self._stubs['autocomplete_places'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.search_nearby: self._wrap_method( - self.search_nearby, - default_timeout=None, - client_info=client_info, - ), - self.search_text: self._wrap_method( - self.search_text, - default_timeout=None, - client_info=client_info, - ), - self.get_photo_media: self._wrap_method( - self.get_photo_media, - default_timeout=None, - client_info=client_info, - ), - self.get_place: self._wrap_method( - self.get_place, - default_timeout=None, - client_info=client_info, - ), - self.autocomplete_places: self._wrap_method( - self.autocomplete_places, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - -__all__ = ( - 'PlacesGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py deleted file mode 100644 index db320d32a841..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest.py +++ /dev/null @@ -1,946 +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 logging -import json # type: ignore - -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 - -from google.protobuf import json_format - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service - - -from .rest_base import _BasePlacesRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - - -class PlacesRestInterceptor: - """Interceptor for Places. - - 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 PlacesRestTransport. - - .. code-block:: python - class MyCustomPlacesInterceptor(PlacesRestInterceptor): - def pre_autocomplete_places(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_autocomplete_places(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_photo_media(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_photo_media(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_place(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_place(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_nearby(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_nearby(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_text(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_text(self, response): - logging.log(f"Received response: {response}") - return response - - transport = PlacesRestTransport(interceptor=MyCustomPlacesInterceptor()) - client = PlacesClient(transport=transport) - - - """ - def pre_autocomplete_places(self, request: places_service.AutocompletePlacesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.AutocompletePlacesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for autocomplete_places - - Override in a subclass to manipulate the request or metadata - before they are sent to the Places server. - """ - return request, metadata - - def post_autocomplete_places(self, response: places_service.AutocompletePlacesResponse) -> places_service.AutocompletePlacesResponse: - """Post-rpc interceptor for autocomplete_places - - Override in a subclass to manipulate the response - after it is returned by the Places server but before - it is returned to user code. - """ - return response - - def pre_get_photo_media(self, request: places_service.GetPhotoMediaRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.GetPhotoMediaRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_photo_media - - Override in a subclass to manipulate the request or metadata - before they are sent to the Places server. - """ - return request, metadata - - def post_get_photo_media(self, response: places_service.PhotoMedia) -> places_service.PhotoMedia: - """Post-rpc interceptor for get_photo_media - - Override in a subclass to manipulate the response - after it is returned by the Places server but before - it is returned to user code. - """ - return response - - def pre_get_place(self, request: places_service.GetPlaceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.GetPlaceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_place - - Override in a subclass to manipulate the request or metadata - before they are sent to the Places server. - """ - return request, metadata - - def post_get_place(self, response: place.Place) -> place.Place: - """Post-rpc interceptor for get_place - - Override in a subclass to manipulate the response - after it is returned by the Places server but before - it is returned to user code. - """ - return response - - def pre_search_nearby(self, request: places_service.SearchNearbyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.SearchNearbyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for search_nearby - - Override in a subclass to manipulate the request or metadata - before they are sent to the Places server. - """ - return request, metadata - - def post_search_nearby(self, response: places_service.SearchNearbyResponse) -> places_service.SearchNearbyResponse: - """Post-rpc interceptor for search_nearby - - Override in a subclass to manipulate the response - after it is returned by the Places server but before - it is returned to user code. - """ - return response - - def pre_search_text(self, request: places_service.SearchTextRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[places_service.SearchTextRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for search_text - - Override in a subclass to manipulate the request or metadata - before they are sent to the Places server. - """ - return request, metadata - - def post_search_text(self, response: places_service.SearchTextResponse) -> places_service.SearchTextResponse: - """Post-rpc interceptor for search_text - - Override in a subclass to manipulate the response - after it is returned by the Places server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class PlacesRestStub: - _session: AuthorizedSession - _host: str - _interceptor: PlacesRestInterceptor - - -class PlacesRestTransport(_BasePlacesRestTransport): - """REST backend synchronous transport for Places. - - Service definition for the Places API. Note: every request (except - for Autocomplete requests) requires a field mask set outside of the - request proto (``all/*``, is not assumed). The field mask can be set - via the HTTP header ``X-Goog-FieldMask``. See: - https://developers.google.com/maps/documentation/places/web-service/choose-fields - - 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 = 'places.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[PlacesRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'places.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or PlacesRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _AutocompletePlaces(_BasePlacesRestTransport._BaseAutocompletePlaces, PlacesRestStub): - def __hash__(self): - return hash("PlacesRestTransport.AutocompletePlaces") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: places_service.AutocompletePlacesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> places_service.AutocompletePlacesResponse: - r"""Call the autocomplete places method over HTTP. - - Args: - request (~.places_service.AutocompletePlacesRequest): - The request object. Request proto for AutocompletePlaces. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.places_service.AutocompletePlacesResponse: - Response proto for - AutocompletePlaces. - - """ - - http_options = _BasePlacesRestTransport._BaseAutocompletePlaces._get_http_options() - - request, metadata = self._interceptor.pre_autocomplete_places(request, metadata) - transcoded_request = _BasePlacesRestTransport._BaseAutocompletePlaces._get_transcoded_request(http_options, request) - - body = _BasePlacesRestTransport._BaseAutocompletePlaces._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BasePlacesRestTransport._BaseAutocompletePlaces._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.maps.places_v1.PlacesClient.AutocompletePlaces", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "AutocompletePlaces", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PlacesRestTransport._AutocompletePlaces._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = places_service.AutocompletePlacesResponse() - pb_resp = places_service.AutocompletePlacesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_autocomplete_places(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = places_service.AutocompletePlacesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.maps.places_v1.PlacesClient.autocomplete_places", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "AutocompletePlaces", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetPhotoMedia(_BasePlacesRestTransport._BaseGetPhotoMedia, PlacesRestStub): - def __hash__(self): - return hash("PlacesRestTransport.GetPhotoMedia") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: places_service.GetPhotoMediaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> places_service.PhotoMedia: - r"""Call the get photo media method over HTTP. - - Args: - request (~.places_service.GetPhotoMediaRequest): - The request object. Request for fetching a photo of a - place using a photo resource name. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.places_service.PhotoMedia: - A photo media from Places API. - """ - - http_options = _BasePlacesRestTransport._BaseGetPhotoMedia._get_http_options() - - request, metadata = self._interceptor.pre_get_photo_media(request, metadata) - transcoded_request = _BasePlacesRestTransport._BaseGetPhotoMedia._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BasePlacesRestTransport._BaseGetPhotoMedia._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.maps.places_v1.PlacesClient.GetPhotoMedia", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "GetPhotoMedia", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PlacesRestTransport._GetPhotoMedia._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = places_service.PhotoMedia() - pb_resp = places_service.PhotoMedia.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_photo_media(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = places_service.PhotoMedia.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.maps.places_v1.PlacesClient.get_photo_media", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "GetPhotoMedia", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetPlace(_BasePlacesRestTransport._BaseGetPlace, PlacesRestStub): - def __hash__(self): - return hash("PlacesRestTransport.GetPlace") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: places_service.GetPlaceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> place.Place: - r"""Call the get place method over HTTP. - - Args: - request (~.places_service.GetPlaceRequest): - The request object. Request for fetching a Place based on its resource name, - which is a string in the ``places/{place_id}`` format. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.place.Place: - All the information representing a - Place. - - """ - - http_options = _BasePlacesRestTransport._BaseGetPlace._get_http_options() - - request, metadata = self._interceptor.pre_get_place(request, metadata) - transcoded_request = _BasePlacesRestTransport._BaseGetPlace._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BasePlacesRestTransport._BaseGetPlace._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.maps.places_v1.PlacesClient.GetPlace", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "GetPlace", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PlacesRestTransport._GetPlace._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # 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 = place.Place() - pb_resp = place.Place.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_place(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = place.Place.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.maps.places_v1.PlacesClient.get_place", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "GetPlace", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _SearchNearby(_BasePlacesRestTransport._BaseSearchNearby, PlacesRestStub): - def __hash__(self): - return hash("PlacesRestTransport.SearchNearby") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: places_service.SearchNearbyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> places_service.SearchNearbyResponse: - r"""Call the search nearby method over HTTP. - - Args: - request (~.places_service.SearchNearbyRequest): - The request object. Request proto for Search Nearby. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.places_service.SearchNearbyResponse: - Response proto for Search Nearby. - """ - - http_options = _BasePlacesRestTransport._BaseSearchNearby._get_http_options() - - request, metadata = self._interceptor.pre_search_nearby(request, metadata) - transcoded_request = _BasePlacesRestTransport._BaseSearchNearby._get_transcoded_request(http_options, request) - - body = _BasePlacesRestTransport._BaseSearchNearby._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BasePlacesRestTransport._BaseSearchNearby._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.maps.places_v1.PlacesClient.SearchNearby", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "SearchNearby", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PlacesRestTransport._SearchNearby._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = places_service.SearchNearbyResponse() - pb_resp = places_service.SearchNearbyResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_search_nearby(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = places_service.SearchNearbyResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.maps.places_v1.PlacesClient.search_nearby", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "SearchNearby", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _SearchText(_BasePlacesRestTransport._BaseSearchText, PlacesRestStub): - def __hash__(self): - return hash("PlacesRestTransport.SearchText") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: places_service.SearchTextRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> places_service.SearchTextResponse: - r"""Call the search text method over HTTP. - - Args: - request (~.places_service.SearchTextRequest): - The request object. Request proto for SearchText. - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.places_service.SearchTextResponse: - Response proto for SearchText. - """ - - http_options = _BasePlacesRestTransport._BaseSearchText._get_http_options() - - request, metadata = self._interceptor.pre_search_text(request, metadata) - transcoded_request = _BasePlacesRestTransport._BaseSearchText._get_transcoded_request(http_options, request) - - body = _BasePlacesRestTransport._BaseSearchText._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BasePlacesRestTransport._BaseSearchText._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.maps.places_v1.PlacesClient.SearchText", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "SearchText", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = PlacesRestTransport._SearchText._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = places_service.SearchTextResponse() - pb_resp = places_service.SearchTextResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_search_text(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = places_service.SearchTextResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.maps.places_v1.PlacesClient.search_text", - extra = { - "serviceName": "google.maps.places.v1.Places", - "rpcName": "SearchText", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def autocomplete_places(self) -> Callable[ - [places_service.AutocompletePlacesRequest], - places_service.AutocompletePlacesResponse]: - # 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._AutocompletePlaces(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_photo_media(self) -> Callable[ - [places_service.GetPhotoMediaRequest], - places_service.PhotoMedia]: - # 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._GetPhotoMedia(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_place(self) -> Callable[ - [places_service.GetPlaceRequest], - place.Place]: - # 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._GetPlace(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_nearby(self) -> Callable[ - [places_service.SearchNearbyRequest], - places_service.SearchNearbyResponse]: - # 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._SearchNearby(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_text(self) -> Callable[ - [places_service.SearchTextRequest], - places_service.SearchTextResponse]: - # 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._SearchText(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'PlacesRestTransport', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py deleted file mode 100644 index b20551b4308c..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/services/places/transports/rest_base.py +++ /dev/null @@ -1,307 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import PlacesTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service - - -class _BasePlacesRestTransport(PlacesTransport): - """Base REST backend transport for Places. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'places.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'places.googleapis.com'). - credentials (Optional[Any]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseAutocompletePlaces: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/places:autocomplete', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = places_service.AutocompletePlacesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BasePlacesRestTransport._BaseAutocompletePlaces._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetPhotoMedia: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=places/*/photos/*/media}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = places_service.GetPhotoMediaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BasePlacesRestTransport._BaseGetPhotoMedia._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetPlace: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=places/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = places_service.GetPlaceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BasePlacesRestTransport._BaseGetPlace._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseSearchNearby: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/places:searchNearby', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = places_service.SearchNearbyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BasePlacesRestTransport._BaseSearchNearby._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseSearchText: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/places:searchText', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = places_service.SearchTextRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BasePlacesRestTransport._BaseSearchText._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BasePlacesRestTransport', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py deleted file mode 100644 index 7795dad518e6..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/__init__.py +++ /dev/null @@ -1,108 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .attribution import ( - AuthorAttribution, -) -from .content_block import ( - ContentBlock, -) -from .contextual_content import ( - ContextualContent, -) -from .ev_charging import ( - EVChargeOptions, - EVConnectorType, -) -from .fuel_options import ( - FuelOptions, -) -from .geometry import ( - Circle, -) -from .photo import ( - Photo, -) -from .place import ( - Place, - PriceLevel, -) -from .places_service import ( - AutocompletePlacesRequest, - AutocompletePlacesResponse, - GetPhotoMediaRequest, - GetPlaceRequest, - PhotoMedia, - RoutingParameters, - SearchNearbyRequest, - SearchNearbyResponse, - SearchTextRequest, - SearchTextResponse, -) -from .polyline import ( - Polyline, -) -from .price_range import ( - PriceRange, -) -from .reference import ( - References, -) -from .review import ( - Review, -) -from .route_modifiers import ( - RouteModifiers, -) -from .routing_preference import ( - RoutingPreference, -) -from .routing_summary import ( - RoutingSummary, -) -from .travel_mode import ( - TravelMode, -) - -__all__ = ( - 'AuthorAttribution', - 'ContentBlock', - 'ContextualContent', - 'EVChargeOptions', - 'EVConnectorType', - 'FuelOptions', - 'Circle', - 'Photo', - 'Place', - 'PriceLevel', - 'AutocompletePlacesRequest', - 'AutocompletePlacesResponse', - 'GetPhotoMediaRequest', - 'GetPlaceRequest', - 'PhotoMedia', - 'RoutingParameters', - 'SearchNearbyRequest', - 'SearchNearbyResponse', - 'SearchTextRequest', - 'SearchTextResponse', - 'Polyline', - 'PriceRange', - 'References', - 'Review', - 'RouteModifiers', - 'RoutingPreference', - 'RoutingSummary', - 'TravelMode', -) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py deleted file mode 100644 index a22226438126..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/attribution.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'AuthorAttribution', - }, -) - - -class AuthorAttribution(proto.Message): - r"""Information about the author of the UGC data. Used in - [Photo][google.maps.places.v1.Photo], and - [Review][google.maps.places.v1.Review]. - - Attributes: - display_name (str): - Name of the author of the - [Photo][google.maps.places.v1.Photo] or - [Review][google.maps.places.v1.Review]. - uri (str): - URI of the author of the - [Photo][google.maps.places.v1.Photo] or - [Review][google.maps.places.v1.Review]. - photo_uri (str): - Profile photo URI of the author of the - [Photo][google.maps.places.v1.Photo] or - [Review][google.maps.places.v1.Review]. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - ) - photo_uri: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py deleted file mode 100644 index d5f47e4b7a99..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/content_block.py +++ /dev/null @@ -1,68 +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.places_v1.types import reference -from google.type import localized_text_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'ContentBlock', - }, -) - - -class ContentBlock(proto.Message): - r"""A block of content that can be served individually. - - Attributes: - topic (str): - The topic of the content, for example - "overview" or "restaurant". - content (google.type.localized_text_pb2.LocalizedText): - Content related to the topic. - references (google.maps.places_v1.types.References): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - References that are related to this block of - content. - """ - - topic: str = proto.Field( - proto.STRING, - number=1, - ) - content: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=2, - message=localized_text_pb2.LocalizedText, - ) - references: reference.References = proto.Field( - proto.MESSAGE, - number=3, - message=reference.References, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py deleted file mode 100644 index d1dbb7caa603..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/contextual_content.py +++ /dev/null @@ -1,218 +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.places_v1.types import photo -from google.maps.places_v1.types import review as gmp_review - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'ContextualContent', - }, -) - - -class ContextualContent(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - Content that is contextual to the place query. - - Attributes: - reviews (MutableSequence[google.maps.places_v1.types.Review]): - List of reviews about this place, contexual - to the place query. - photos (MutableSequence[google.maps.places_v1.types.Photo]): - Information (including references) about - photos of this place, contexual to the place - query. - justifications (MutableSequence[google.maps.places_v1.types.ContextualContent.Justification]): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - Justifications for the place. - """ - - class Justification(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - Justifications for the place. Justifications answers the - question of why a place could interest an end user. - - 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: - review_justification (google.maps.places_v1.types.ContextualContent.Justification.ReviewJustification): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - This field is a member of `oneof`_ ``justification``. - business_availability_attributes_justification (google.maps.places_v1.types.ContextualContent.Justification.BusinessAvailabilityAttributesJustification): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - This field is a member of `oneof`_ ``justification``. - """ - - class ReviewJustification(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - User review justifications. This highlights a section of the - user review that would interest an end user. For instance, if - the search query is "firewood pizza", the review justification - highlights the text relevant to the search query. - - Attributes: - highlighted_text (google.maps.places_v1.types.ContextualContent.Justification.ReviewJustification.HighlightedText): - - review (google.maps.places_v1.types.Review): - The review that the highlighted text is - generated from. - """ - - class HighlightedText(proto.Message): - r"""The text highlighted by the justification. This is a subset - of the review itself. The exact word to highlight is marked by - the HighlightedTextRange. There could be several words in the - text being highlighted. - - Attributes: - text (str): - - highlighted_text_ranges (MutableSequence[google.maps.places_v1.types.ContextualContent.Justification.ReviewJustification.HighlightedText.HighlightedTextRange]): - The list of the ranges of the highlighted - text. - """ - - class HighlightedTextRange(proto.Message): - r"""The range of highlighted text. - - Attributes: - start_index (int): - - end_index (int): - - """ - - start_index: int = proto.Field( - proto.INT32, - number=1, - ) - end_index: int = proto.Field( - proto.INT32, - number=2, - ) - - text: str = proto.Field( - proto.STRING, - number=1, - ) - highlighted_text_ranges: MutableSequence['ContextualContent.Justification.ReviewJustification.HighlightedText.HighlightedTextRange'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ContextualContent.Justification.ReviewJustification.HighlightedText.HighlightedTextRange', - ) - - highlighted_text: 'ContextualContent.Justification.ReviewJustification.HighlightedText' = proto.Field( - proto.MESSAGE, - number=1, - message='ContextualContent.Justification.ReviewJustification.HighlightedText', - ) - review: gmp_review.Review = proto.Field( - proto.MESSAGE, - number=2, - message=gmp_review.Review, - ) - - class BusinessAvailabilityAttributesJustification(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - BusinessAvailabilityAttributes justifications. This shows some - attributes a business has that could interest an end user. - - Attributes: - takeout (bool): - If a place provides takeout. - delivery (bool): - If a place provides delivery. - dine_in (bool): - If a place provides dine-in. - """ - - takeout: bool = proto.Field( - proto.BOOL, - number=1, - ) - delivery: bool = proto.Field( - proto.BOOL, - number=2, - ) - dine_in: bool = proto.Field( - proto.BOOL, - number=3, - ) - - review_justification: 'ContextualContent.Justification.ReviewJustification' = proto.Field( - proto.MESSAGE, - number=1, - oneof='justification', - message='ContextualContent.Justification.ReviewJustification', - ) - business_availability_attributes_justification: 'ContextualContent.Justification.BusinessAvailabilityAttributesJustification' = proto.Field( - proto.MESSAGE, - number=2, - oneof='justification', - message='ContextualContent.Justification.BusinessAvailabilityAttributesJustification', - ) - - reviews: MutableSequence[gmp_review.Review] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gmp_review.Review, - ) - photos: MutableSequence[photo.Photo] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=photo.Photo, - ) - justifications: MutableSequence[Justification] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=Justification, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py deleted file mode 100644 index 17763d21f927..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/ev_charging.py +++ /dev/null @@ -1,176 +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 - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'EVConnectorType', - 'EVChargeOptions', - }, -) - - -class EVConnectorType(proto.Enum): - r"""See - http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=6872107 for - additional information/context on EV charging connector types. - - Values: - EV_CONNECTOR_TYPE_UNSPECIFIED (0): - Unspecified connector. - EV_CONNECTOR_TYPE_OTHER (1): - Other connector types. - EV_CONNECTOR_TYPE_J1772 (2): - J1772 type 1 connector. - EV_CONNECTOR_TYPE_TYPE_2 (3): - IEC 62196 type 2 connector. Often referred to - as MENNEKES. - EV_CONNECTOR_TYPE_CHADEMO (4): - CHAdeMO type connector. - EV_CONNECTOR_TYPE_CCS_COMBO_1 (5): - Combined Charging System (AC and DC). Based - on SAE. Type-1 J-1772 connector - EV_CONNECTOR_TYPE_CCS_COMBO_2 (6): - Combined Charging System (AC and DC). Based - on Type-2 Mennekes connector - EV_CONNECTOR_TYPE_TESLA (7): - The generic TESLA connector. This is NACS in - the North America but can be non-NACS in other - parts of the world (e.g. CCS Combo 2 (CCS2) or - GB/T). This value is less representative of an - actual connector type, and more represents the - ability to charge a Tesla brand vehicle at a - Tesla owned charging station. - EV_CONNECTOR_TYPE_UNSPECIFIED_GB_T (8): - GB/T type corresponds to the GB/T standard in China. This - type covers all GB_T types. - EV_CONNECTOR_TYPE_UNSPECIFIED_WALL_OUTLET (9): - Unspecified wall outlet. - """ - EV_CONNECTOR_TYPE_UNSPECIFIED = 0 - EV_CONNECTOR_TYPE_OTHER = 1 - EV_CONNECTOR_TYPE_J1772 = 2 - EV_CONNECTOR_TYPE_TYPE_2 = 3 - EV_CONNECTOR_TYPE_CHADEMO = 4 - EV_CONNECTOR_TYPE_CCS_COMBO_1 = 5 - EV_CONNECTOR_TYPE_CCS_COMBO_2 = 6 - EV_CONNECTOR_TYPE_TESLA = 7 - EV_CONNECTOR_TYPE_UNSPECIFIED_GB_T = 8 - EV_CONNECTOR_TYPE_UNSPECIFIED_WALL_OUTLET = 9 - - -class EVChargeOptions(proto.Message): - r"""Information about the EV Charge Station hosted in Place. Terminology - follows - https://afdc.energy.gov/fuels/electricity_infrastructure.html One - port could charge one car at a time. One port has one or more - connectors. One station has one or more ports. - - Attributes: - connector_count (int): - Number of connectors at this station. - However, because some ports can have multiple - connectors but only be able to charge one car at - a time (e.g.) the number of connectors may be - greater than the total number of cars which can - charge simultaneously. - connector_aggregation (MutableSequence[google.maps.places_v1.types.EVChargeOptions.ConnectorAggregation]): - A list of EV charging connector aggregations - that contain connectors of the same type and - same charge rate. - """ - - class ConnectorAggregation(proto.Message): - r"""EV charging information grouped by [type, max_charge_rate_kw]. Shows - EV charge aggregation of connectors that have the same type and max - charge rate in kw. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - type_ (google.maps.places_v1.types.EVConnectorType): - The connector type of this aggregation. - max_charge_rate_kw (float): - The static max charging rate in kw of each - connector in the aggregation. - count (int): - Number of connectors in this aggregation. - available_count (int): - Number of connectors in this aggregation that - are currently available. - - This field is a member of `oneof`_ ``_available_count``. - out_of_service_count (int): - Number of connectors in this aggregation that - are currently out of service. - - This field is a member of `oneof`_ ``_out_of_service_count``. - availability_last_update_time (google.protobuf.timestamp_pb2.Timestamp): - The timestamp when the connector availability - information in this aggregation was last - updated. - """ - - type_: 'EVConnectorType' = proto.Field( - proto.ENUM, - number=1, - enum='EVConnectorType', - ) - max_charge_rate_kw: float = proto.Field( - proto.DOUBLE, - number=2, - ) - count: int = proto.Field( - proto.INT32, - number=3, - ) - available_count: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - out_of_service_count: int = proto.Field( - proto.INT32, - number=5, - optional=True, - ) - availability_last_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - connector_count: int = proto.Field( - proto.INT32, - number=1, - ) - connector_aggregation: MutableSequence[ConnectorAggregation] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=ConnectorAggregation, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py deleted file mode 100644 index 8207d12611bd..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/fuel_options.py +++ /dev/null @@ -1,149 +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.type import money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'FuelOptions', - }, -) - - -class FuelOptions(proto.Message): - r"""The most recent information about fuel options in a gas - station. This information is updated regularly. - - Attributes: - fuel_prices (MutableSequence[google.maps.places_v1.types.FuelOptions.FuelPrice]): - The last known fuel price for each type of - fuel this station has. There is one entry per - fuel type this station has. Order is not - important. - """ - - class FuelPrice(proto.Message): - r"""Fuel price information for a given type. - - Attributes: - type_ (google.maps.places_v1.types.FuelOptions.FuelPrice.FuelType): - The type of fuel. - price (google.type.money_pb2.Money): - The price of the fuel. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time the fuel price was last updated. - """ - class FuelType(proto.Enum): - r"""Types of fuel. - - Values: - FUEL_TYPE_UNSPECIFIED (0): - Unspecified fuel type. - DIESEL (1): - Diesel fuel. - DIESEL_PLUS (19): - Diesel plus fuel. - REGULAR_UNLEADED (2): - Regular unleaded. - MIDGRADE (3): - Midgrade. - PREMIUM (4): - Premium. - SP91 (5): - SP 91. - SP91_E10 (6): - SP 91 E10. - SP92 (7): - SP 92. - SP95 (8): - SP 95. - SP95_E10 (9): - SP95 E10. - SP98 (10): - SP 98. - SP99 (11): - SP 99. - SP100 (12): - SP 100. - LPG (13): - Liquefied Petroleum Gas. - E80 (14): - E 80. - E85 (15): - E 85. - E100 (20): - E 100. - METHANE (16): - Methane. - BIO_DIESEL (17): - Bio-diesel. - TRUCK_DIESEL (18): - Truck diesel. - """ - FUEL_TYPE_UNSPECIFIED = 0 - DIESEL = 1 - DIESEL_PLUS = 19 - REGULAR_UNLEADED = 2 - MIDGRADE = 3 - PREMIUM = 4 - SP91 = 5 - SP91_E10 = 6 - SP92 = 7 - SP95 = 8 - SP95_E10 = 9 - SP98 = 10 - SP99 = 11 - SP100 = 12 - LPG = 13 - E80 = 14 - E85 = 15 - E100 = 20 - METHANE = 16 - BIO_DIESEL = 17 - TRUCK_DIESEL = 18 - - type_: 'FuelOptions.FuelPrice.FuelType' = proto.Field( - proto.ENUM, - number=1, - enum='FuelOptions.FuelPrice.FuelType', - ) - price: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - message=money_pb2.Money, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - fuel_prices: MutableSequence[FuelPrice] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=FuelPrice, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py deleted file mode 100644 index b3d1cf8c1eb3..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/geometry.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'Circle', - }, -) - - -class Circle(proto.Message): - r"""Circle with a LatLng as center and radius. - - Attributes: - center (google.type.latlng_pb2.LatLng): - Required. Center latitude and longitude. - - The range of latitude must be within [-90.0, 90.0]. The - range of the longitude must be within [-180.0, 180.0]. - radius (float): - Required. Radius measured in meters. The radius must be - within [0.0, 50000.0]. - """ - - center: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - radius: float = proto.Field( - proto.DOUBLE, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py deleted file mode 100644 index 45bc33ecb53e..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/photo.py +++ /dev/null @@ -1,69 +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.places_v1.types import attribution - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'Photo', - }, -) - - -class Photo(proto.Message): - r"""Information about a photo of a place. - - Attributes: - name (str): - Identifier. A reference representing this place photo which - may be used to look up this place photo again (also called - the API "resource" name: - ``places/{place_id}/photos/{photo}``). - width_px (int): - The maximum available width, in pixels. - height_px (int): - The maximum available height, in pixels. - author_attributions (MutableSequence[google.maps.places_v1.types.AuthorAttribution]): - This photo's authors. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - width_px: int = proto.Field( - proto.INT32, - number=2, - ) - height_px: int = proto.Field( - proto.INT32, - number=3, - ) - author_attributions: MutableSequence[attribution.AuthorAttribution] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=attribution.AuthorAttribution, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py deleted file mode 100644 index 34e44adedb46..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/place.py +++ /dev/null @@ -1,1286 +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.places_v1.types import content_block -from google.maps.places_v1.types import ev_charging -from google.maps.places_v1.types import fuel_options as gmp_fuel_options -from google.maps.places_v1.types import photo -from google.maps.places_v1.types import price_range as gmp_price_range -from google.maps.places_v1.types import reference -from google.maps.places_v1.types import review -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'PriceLevel', - 'Place', - }, -) - - -class PriceLevel(proto.Enum): - r"""Price level of the place. - - Values: - PRICE_LEVEL_UNSPECIFIED (0): - Place price level is unspecified or unknown. - PRICE_LEVEL_FREE (1): - Place provides free services. - PRICE_LEVEL_INEXPENSIVE (2): - Place provides inexpensive services. - PRICE_LEVEL_MODERATE (3): - Place provides moderately priced services. - PRICE_LEVEL_EXPENSIVE (4): - Place provides expensive services. - PRICE_LEVEL_VERY_EXPENSIVE (5): - Place provides very expensive services. - """ - PRICE_LEVEL_UNSPECIFIED = 0 - PRICE_LEVEL_FREE = 1 - PRICE_LEVEL_INEXPENSIVE = 2 - PRICE_LEVEL_MODERATE = 3 - PRICE_LEVEL_EXPENSIVE = 4 - PRICE_LEVEL_VERY_EXPENSIVE = 5 - - -class Place(proto.Message): - r"""All the information representing a Place. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - This Place's resource name, in ``places/{place_id}`` format. - Can be used to look up the Place. - id (str): - The unique identifier of a place. - display_name (google.type.localized_text_pb2.LocalizedText): - The localized name of the place, suitable as - a short human-readable description. For example, - "Google Sydney", "Starbucks", "Pyrmont", etc. - types (MutableSequence[str]): - A set of type tags for this result. For - example, "political" and "locality". For the - complete list of possible values, see Table A - and Table B at - https://developers.google.com/maps/documentation/places/web-service/place-types - primary_type (str): - The primary type of the given result. This - type must one of the Places API supported types. - For example, "restaurant", "cafe", "airport", - etc. A place can only have a single primary - type. For the complete list of possible values, - see Table A and Table B at - https://developers.google.com/maps/documentation/places/web-service/place-types - primary_type_display_name (google.type.localized_text_pb2.LocalizedText): - The display name of the primary type, - localized to the request language if applicable. - For the complete list of possible values, see - Table A and Table B at - https://developers.google.com/maps/documentation/places/web-service/place-types - national_phone_number (str): - A human-readable phone number for the place, - in national format. - international_phone_number (str): - A human-readable phone number for the place, - in international format. - formatted_address (str): - A full, human-readable address for this - place. - short_formatted_address (str): - A short, human-readable address for this - place. - address_components (MutableSequence[google.maps.places_v1.types.Place.AddressComponent]): - Repeated components for each locality level. Note the - following facts about the address_components[] array: - - - The array of address components may contain more - components than the formatted_address. - - The array does not necessarily include all the political - entities that contain an address, apart from those - included in the formatted_address. To retrieve all the - political entities that contain a specific address, you - should use reverse geocoding, passing the - latitude/longitude of the address as a parameter to the - request. - - The format of the response is not guaranteed to remain - the same between requests. In particular, the number of - address_components varies based on the address requested - and can change over time for the same address. A - component can change position in the array. The type of - the component can change. A particular component may be - missing in a later response. - plus_code (google.maps.places_v1.types.Place.PlusCode): - Plus code of the place location lat/long. - location (google.type.latlng_pb2.LatLng): - The position of this place. - viewport (google.geo.type.types.Viewport): - A viewport suitable for displaying the place - on an average-sized map. This viewport should - not be used as the physical boundary or the - service area of the business. - rating (float): - A rating between 1.0 and 5.0, based on user - reviews of this place. - google_maps_uri (str): - A URL providing more information about this - place. - website_uri (str): - The authoritative website for this place, - e.g. a business' homepage. Note that for places - that are part of a chain (e.g. an IKEA store), - this will usually be the website for the - individual store, not the overall chain. - reviews (MutableSequence[google.maps.places_v1.types.Review]): - List of reviews about this place, sorted by - relevance. A maximum of 5 reviews can be - returned. - regular_opening_hours (google.maps.places_v1.types.Place.OpeningHours): - The regular hours of operation. - utc_offset_minutes (int): - Number of minutes this place's timezone is - currently offset from UTC. This is expressed in - minutes to support timezones that are offset by - fractions of an hour, e.g. X hours and 15 - minutes. - - This field is a member of `oneof`_ ``_utc_offset_minutes``. - photos (MutableSequence[google.maps.places_v1.types.Photo]): - Information (including references) about - photos of this place. A maximum of 10 photos can - be returned. - adr_format_address (str): - The place's address in adr microformat: - http://microformats.org/wiki/adr. - business_status (google.maps.places_v1.types.Place.BusinessStatus): - - price_level (google.maps.places_v1.types.PriceLevel): - Price level of the place. - attributions (MutableSequence[google.maps.places_v1.types.Place.Attribution]): - A set of data provider that must be shown - with this result. - user_rating_count (int): - The total number of reviews (with or without - text) for this place. - - This field is a member of `oneof`_ ``_user_rating_count``. - icon_mask_base_uri (str): - A truncated URL to an icon mask. User can - access different icon type by appending type - suffix to the end (eg, ".svg" or ".png"). - icon_background_color (str): - Background color for icon_mask in hex format, e.g. #909CE1. - takeout (bool): - Specifies if the business supports takeout. - - This field is a member of `oneof`_ ``_takeout``. - delivery (bool): - Specifies if the business supports delivery. - - This field is a member of `oneof`_ ``_delivery``. - dine_in (bool): - Specifies if the business supports indoor or - outdoor seating options. - - This field is a member of `oneof`_ ``_dine_in``. - curbside_pickup (bool): - Specifies if the business supports curbside - pickup. - - This field is a member of `oneof`_ ``_curbside_pickup``. - reservable (bool): - Specifies if the place supports reservations. - - This field is a member of `oneof`_ ``_reservable``. - serves_breakfast (bool): - Specifies if the place serves breakfast. - - This field is a member of `oneof`_ ``_serves_breakfast``. - serves_lunch (bool): - Specifies if the place serves lunch. - - This field is a member of `oneof`_ ``_serves_lunch``. - serves_dinner (bool): - Specifies if the place serves dinner. - - This field is a member of `oneof`_ ``_serves_dinner``. - serves_beer (bool): - Specifies if the place serves beer. - - This field is a member of `oneof`_ ``_serves_beer``. - serves_wine (bool): - Specifies if the place serves wine. - - This field is a member of `oneof`_ ``_serves_wine``. - serves_brunch (bool): - Specifies if the place serves brunch. - - This field is a member of `oneof`_ ``_serves_brunch``. - serves_vegetarian_food (bool): - Specifies if the place serves vegetarian - food. - - This field is a member of `oneof`_ ``_serves_vegetarian_food``. - current_opening_hours (google.maps.places_v1.types.Place.OpeningHours): - The hours of operation for the next seven days (including - today). The time period starts at midnight on the date of - the request and ends at 11:59 pm six days later. This field - includes the special_days subfield of all hours, set for - dates that have exceptional hours. - current_secondary_opening_hours (MutableSequence[google.maps.places_v1.types.Place.OpeningHours]): - Contains an array of entries for the next seven days - including information about secondary hours of a business. - Secondary hours are different from a business's main hours. - For example, a restaurant can specify drive through hours or - delivery hours as its secondary hours. This field populates - the type subfield, which draws from a predefined list of - opening hours types (such as DRIVE_THROUGH, PICKUP, or - TAKEOUT) based on the types of the place. This field - includes the special_days subfield of all hours, set for - dates that have exceptional hours. - regular_secondary_opening_hours (MutableSequence[google.maps.places_v1.types.Place.OpeningHours]): - Contains an array of entries for information about regular - secondary hours of a business. Secondary hours are different - from a business's main hours. For example, a restaurant can - specify drive through hours or delivery hours as its - secondary hours. This field populates the type subfield, - which draws from a predefined list of opening hours types - (such as DRIVE_THROUGH, PICKUP, or TAKEOUT) based on the - types of the place. - editorial_summary (google.type.localized_text_pb2.LocalizedText): - Contains a summary of the place. A summary is - comprised of a textual overview, and also - includes the language code for these if - applicable. Summary text must be presented as-is - and can not be modified or altered. - outdoor_seating (bool): - Place provides outdoor seating. - - This field is a member of `oneof`_ ``_outdoor_seating``. - live_music (bool): - Place provides live music. - - This field is a member of `oneof`_ ``_live_music``. - menu_for_children (bool): - Place has a children's menu. - - This field is a member of `oneof`_ ``_menu_for_children``. - serves_cocktails (bool): - Place serves cocktails. - - This field is a member of `oneof`_ ``_serves_cocktails``. - serves_dessert (bool): - Place serves dessert. - - This field is a member of `oneof`_ ``_serves_dessert``. - serves_coffee (bool): - Place serves coffee. - - This field is a member of `oneof`_ ``_serves_coffee``. - good_for_children (bool): - Place is good for children. - - This field is a member of `oneof`_ ``_good_for_children``. - allows_dogs (bool): - Place allows dogs. - - This field is a member of `oneof`_ ``_allows_dogs``. - restroom (bool): - Place has restroom. - - This field is a member of `oneof`_ ``_restroom``. - good_for_groups (bool): - Place accommodates groups. - - This field is a member of `oneof`_ ``_good_for_groups``. - good_for_watching_sports (bool): - Place is suitable for watching sports. - - This field is a member of `oneof`_ ``_good_for_watching_sports``. - payment_options (google.maps.places_v1.types.Place.PaymentOptions): - Payment options the place accepts. If a - payment option data is not available, the - payment option field will be unset. - parking_options (google.maps.places_v1.types.Place.ParkingOptions): - Options of parking provided by the place. - sub_destinations (MutableSequence[google.maps.places_v1.types.Place.SubDestination]): - A list of sub destinations related to the - place. - accessibility_options (google.maps.places_v1.types.Place.AccessibilityOptions): - Information about the accessibility options a - place offers. - - This field is a member of `oneof`_ ``_accessibility_options``. - fuel_options (google.maps.places_v1.types.FuelOptions): - The most recent information about fuel - options in a gas station. This information is - updated regularly. - ev_charge_options (google.maps.places_v1.types.EVChargeOptions): - Information of ev charging options. - generative_summary (google.maps.places_v1.types.Place.GenerativeSummary): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - AI-generated summary of the place. - area_summary (google.maps.places_v1.types.Place.AreaSummary): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - AI-generated summary of the area that the place - is in. - containing_places (MutableSequence[google.maps.places_v1.types.Place.ContainingPlace]): - List of places in which the current place is - located. - pure_service_area_business (bool): - Indicates whether the place is a pure service - area business. Pure service area business is a - business that visits or delivers to customers - directly but does not serve customers at their - business address. For example, businesses like - cleaning services or plumbers. Those businesses - may not have a physical address or location on - Google Maps. - - This field is a member of `oneof`_ ``_pure_service_area_business``. - price_range (google.maps.places_v1.types.PriceRange): - The price range associated with a Place. - """ - class BusinessStatus(proto.Enum): - r"""Business status for the place. - - Values: - BUSINESS_STATUS_UNSPECIFIED (0): - Default value. This value is unused. - OPERATIONAL (1): - The establishment is operational, not - necessarily open now. - CLOSED_TEMPORARILY (2): - The establishment is temporarily closed. - CLOSED_PERMANENTLY (3): - The establishment is permanently closed. - """ - BUSINESS_STATUS_UNSPECIFIED = 0 - OPERATIONAL = 1 - CLOSED_TEMPORARILY = 2 - CLOSED_PERMANENTLY = 3 - - class AddressComponent(proto.Message): - r"""The structured components that form the formatted address, if - this information is available. - - Attributes: - long_text (str): - The full text description or name of the address component. - For example, an address component for the country Australia - may have a long_name of "Australia". - short_text (str): - An abbreviated textual name for the address component, if - available. For example, an address component for the country - of Australia may have a short_name of "AU". - types (MutableSequence[str]): - An array indicating the type(s) of the - address component. - language_code (str): - The language used to format this components, - in CLDR notation. - """ - - long_text: str = proto.Field( - proto.STRING, - number=1, - ) - short_text: str = proto.Field( - proto.STRING, - number=2, - ) - types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - language_code: str = proto.Field( - proto.STRING, - number=4, - ) - - class PlusCode(proto.Message): - r"""Plus code (http://plus.codes) is a location reference with - two formats: global code defining a 14mx14m (1/8000th of a - degree) or smaller rectangle, and compound code, replacing the - prefix with a reference location. - - Attributes: - global_code (str): - Place's global (full) code, such as - "9FWM33GV+HQ", representing an 1/8000 by 1/8000 - degree area (~14 by 14 meters). - compound_code (str): - Place's compound code, such as "33GV+HQ, - Ramberg, Norway", containing the suffix of the - global code and replacing the prefix with a - formatted name of a reference entity. - """ - - global_code: str = proto.Field( - proto.STRING, - number=1, - ) - compound_code: str = proto.Field( - proto.STRING, - number=2, - ) - - class OpeningHours(proto.Message): - r"""Information about business hour of the place. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - open_now (bool): - Whether the opening hours period is currently - active. For regular opening hours and current - opening hours, this field means whether the - place is open. For secondary opening hours and - current secondary opening hours, this field - means whether the secondary hours of this place - is active. - - This field is a member of `oneof`_ ``_open_now``. - periods (MutableSequence[google.maps.places_v1.types.Place.OpeningHours.Period]): - The periods that this place is open during - the week. The periods are in chronological - order, starting with Sunday in the place-local - timezone. An empty (but not absent) value - indicates a place that is never open, e.g. - because it is closed temporarily for - renovations. - weekday_descriptions (MutableSequence[str]): - Localized strings describing the opening - hours of this place, one string for each day of - the week. Will be empty if the hours are - unknown or could not be converted to localized - text. Example: "Sun: 18:00–06:00". - secondary_hours_type (google.maps.places_v1.types.Place.OpeningHours.SecondaryHoursType): - A type string used to identify the type of - secondary hours. - special_days (MutableSequence[google.maps.places_v1.types.Place.OpeningHours.SpecialDay]): - Structured information for special days that fall within the - period that the returned opening hours cover. Special days - are days that could impact the business hours of a place, - e.g. Christmas day. Set for current_opening_hours and - current_secondary_opening_hours if there are exceptional - hours. - next_open_time (google.protobuf.timestamp_pb2.Timestamp): - The next time the current opening hours - period starts up to 7 days in the future. This - field is only populated if the opening hours - period is not active at the time of serving the - request. - next_close_time (google.protobuf.timestamp_pb2.Timestamp): - The next time the current opening hours - period ends up to 7 days in the future. This - field is only populated if the opening hours - period is active at the time of serving the - request. - """ - class SecondaryHoursType(proto.Enum): - r"""A type used to identify the type of secondary hours. - - Values: - SECONDARY_HOURS_TYPE_UNSPECIFIED (0): - Default value when secondary hour type is not - specified. - DRIVE_THROUGH (1): - The drive-through hour for banks, - restaurants, or pharmacies. - HAPPY_HOUR (2): - The happy hour. - DELIVERY (3): - The delivery hour. - TAKEOUT (4): - The takeout hour. - KITCHEN (5): - The kitchen hour. - BREAKFAST (6): - The breakfast hour. - LUNCH (7): - The lunch hour. - DINNER (8): - The dinner hour. - BRUNCH (9): - The brunch hour. - PICKUP (10): - The pickup hour. - ACCESS (11): - The access hours for storage places. - SENIOR_HOURS (12): - The special hours for seniors. - ONLINE_SERVICE_HOURS (13): - The online service hours. - """ - SECONDARY_HOURS_TYPE_UNSPECIFIED = 0 - DRIVE_THROUGH = 1 - HAPPY_HOUR = 2 - DELIVERY = 3 - TAKEOUT = 4 - KITCHEN = 5 - BREAKFAST = 6 - LUNCH = 7 - DINNER = 8 - BRUNCH = 9 - PICKUP = 10 - ACCESS = 11 - SENIOR_HOURS = 12 - ONLINE_SERVICE_HOURS = 13 - - class Period(proto.Message): - r"""A period the place remains in open_now status. - - Attributes: - open_ (google.maps.places_v1.types.Place.OpeningHours.Period.Point): - The time that the place starts to be open. - close (google.maps.places_v1.types.Place.OpeningHours.Period.Point): - The time that the place starts to be closed. - """ - - class Point(proto.Message): - r"""Status changing points. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - day (int): - A day of the week, as an integer in the range - 0-6. 0 is Sunday, 1 is Monday, etc. - - This field is a member of `oneof`_ ``_day``. - hour (int): - The hour in 2 digits. Ranges from 00 to 23. - - This field is a member of `oneof`_ ``_hour``. - minute (int): - The minute in 2 digits. Ranges from 00 to 59. - - This field is a member of `oneof`_ ``_minute``. - date (google.type.date_pb2.Date): - Date in the local timezone for the place. - truncated (bool): - Whether or not this endpoint was truncated. Truncation - occurs when the real hours are outside the times we are - willing to return hours between, so we truncate the hours - back to these boundaries. This ensures that at most 24 \* 7 - hours from midnight of the day of the request are returned. - """ - - day: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - hour: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - minute: int = proto.Field( - proto.INT32, - number=3, - optional=True, - ) - date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=6, - message=date_pb2.Date, - ) - truncated: bool = proto.Field( - proto.BOOL, - number=5, - ) - - open_: 'Place.OpeningHours.Period.Point' = proto.Field( - proto.MESSAGE, - number=1, - message='Place.OpeningHours.Period.Point', - ) - close: 'Place.OpeningHours.Period.Point' = proto.Field( - proto.MESSAGE, - number=2, - message='Place.OpeningHours.Period.Point', - ) - - class SpecialDay(proto.Message): - r"""Structured information for special days that fall within the - period that the returned opening hours cover. Special days are - days that could impact the business hours of a place, e.g. - Christmas day. - - Attributes: - date (google.type.date_pb2.Date): - The date of this special day. - """ - - date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=1, - message=date_pb2.Date, - ) - - open_now: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - periods: MutableSequence['Place.OpeningHours.Period'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Place.OpeningHours.Period', - ) - weekday_descriptions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - secondary_hours_type: 'Place.OpeningHours.SecondaryHoursType' = proto.Field( - proto.ENUM, - number=4, - enum='Place.OpeningHours.SecondaryHoursType', - ) - special_days: MutableSequence['Place.OpeningHours.SpecialDay'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='Place.OpeningHours.SpecialDay', - ) - next_open_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - next_close_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - - class Attribution(proto.Message): - r"""Information about data providers of this place. - - Attributes: - provider (str): - Name of the Place's data provider. - provider_uri (str): - URI to the Place's data provider. - """ - - provider: str = proto.Field( - proto.STRING, - number=1, - ) - provider_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - class PaymentOptions(proto.Message): - r"""Payment options the place accepts. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - accepts_credit_cards (bool): - Place accepts credit cards as payment. - - This field is a member of `oneof`_ ``_accepts_credit_cards``. - accepts_debit_cards (bool): - Place accepts debit cards as payment. - - This field is a member of `oneof`_ ``_accepts_debit_cards``. - accepts_cash_only (bool): - Place accepts cash only as payment. Places - with this attribute may still accept other - payment methods. - - This field is a member of `oneof`_ ``_accepts_cash_only``. - accepts_nfc (bool): - Place accepts NFC payments. - - This field is a member of `oneof`_ ``_accepts_nfc``. - """ - - accepts_credit_cards: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - accepts_debit_cards: bool = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - accepts_cash_only: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - accepts_nfc: bool = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - class ParkingOptions(proto.Message): - r"""Information about parking options for the place. A parking - lot could support more than one option at the same time. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - free_parking_lot (bool): - Place offers free parking lots. - - This field is a member of `oneof`_ ``_free_parking_lot``. - paid_parking_lot (bool): - Place offers paid parking lots. - - This field is a member of `oneof`_ ``_paid_parking_lot``. - free_street_parking (bool): - Place offers free street parking. - - This field is a member of `oneof`_ ``_free_street_parking``. - paid_street_parking (bool): - Place offers paid street parking. - - This field is a member of `oneof`_ ``_paid_street_parking``. - valet_parking (bool): - Place offers valet parking. - - This field is a member of `oneof`_ ``_valet_parking``. - free_garage_parking (bool): - Place offers free garage parking. - - This field is a member of `oneof`_ ``_free_garage_parking``. - paid_garage_parking (bool): - Place offers paid garage parking. - - This field is a member of `oneof`_ ``_paid_garage_parking``. - """ - - free_parking_lot: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - paid_parking_lot: bool = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - free_street_parking: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - paid_street_parking: bool = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - valet_parking: bool = proto.Field( - proto.BOOL, - number=5, - optional=True, - ) - free_garage_parking: bool = proto.Field( - proto.BOOL, - number=6, - optional=True, - ) - paid_garage_parking: bool = proto.Field( - proto.BOOL, - number=7, - optional=True, - ) - - class SubDestination(proto.Message): - r"""Place resource name and id of sub destinations that relate to - the place. For example, different terminals are different - destinations of an airport. - - Attributes: - name (str): - The resource name of the sub destination. - id (str): - The place id of the sub destination. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - - class AccessibilityOptions(proto.Message): - r"""Information about the accessibility options a place offers. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - wheelchair_accessible_parking (bool): - Place offers wheelchair accessible parking. - - This field is a member of `oneof`_ ``_wheelchair_accessible_parking``. - wheelchair_accessible_entrance (bool): - Places has wheelchair accessible entrance. - - This field is a member of `oneof`_ ``_wheelchair_accessible_entrance``. - wheelchair_accessible_restroom (bool): - Place has wheelchair accessible restroom. - - This field is a member of `oneof`_ ``_wheelchair_accessible_restroom``. - wheelchair_accessible_seating (bool): - Place has wheelchair accessible seating. - - This field is a member of `oneof`_ ``_wheelchair_accessible_seating``. - """ - - wheelchair_accessible_parking: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - wheelchair_accessible_entrance: bool = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - wheelchair_accessible_restroom: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - wheelchair_accessible_seating: bool = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - class GenerativeSummary(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - AI-generated summary of the place. - - Attributes: - overview (google.type.localized_text_pb2.LocalizedText): - The overview of the place. - description (google.type.localized_text_pb2.LocalizedText): - The detailed description of the place. - references (google.maps.places_v1.types.References): - References that are used to generate the - summary description. - """ - - overview: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=1, - message=localized_text_pb2.LocalizedText, - ) - description: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=2, - message=localized_text_pb2.LocalizedText, - ) - references: reference.References = proto.Field( - proto.MESSAGE, - number=3, - message=reference.References, - ) - - class AreaSummary(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - AI-generated summary of the area that the place is in. - - Attributes: - content_blocks (MutableSequence[google.maps.places_v1.types.ContentBlock]): - Content blocks that compose the area summary. - Each block has a separate topic about the area. - """ - - content_blocks: MutableSequence[content_block.ContentBlock] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=content_block.ContentBlock, - ) - - class ContainingPlace(proto.Message): - r"""Info about the place in which this place is located. - - Attributes: - name (str): - The resource name of the place in which this - place is located. - id (str): - The place id of the place in which this place - is located. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=31, - message=localized_text_pb2.LocalizedText, - ) - types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - primary_type: str = proto.Field( - proto.STRING, - number=50, - ) - primary_type_display_name: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=32, - message=localized_text_pb2.LocalizedText, - ) - national_phone_number: str = proto.Field( - proto.STRING, - number=7, - ) - international_phone_number: str = proto.Field( - proto.STRING, - number=8, - ) - formatted_address: str = proto.Field( - proto.STRING, - number=9, - ) - short_formatted_address: str = proto.Field( - proto.STRING, - number=51, - ) - address_components: MutableSequence[AddressComponent] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=AddressComponent, - ) - plus_code: PlusCode = proto.Field( - proto.MESSAGE, - number=11, - message=PlusCode, - ) - location: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=12, - message=latlng_pb2.LatLng, - ) - viewport: ggt_viewport.Viewport = proto.Field( - proto.MESSAGE, - number=13, - message=ggt_viewport.Viewport, - ) - rating: float = proto.Field( - proto.DOUBLE, - number=14, - ) - google_maps_uri: str = proto.Field( - proto.STRING, - number=15, - ) - website_uri: str = proto.Field( - proto.STRING, - number=16, - ) - reviews: MutableSequence[review.Review] = proto.RepeatedField( - proto.MESSAGE, - number=53, - message=review.Review, - ) - regular_opening_hours: OpeningHours = proto.Field( - proto.MESSAGE, - number=21, - message=OpeningHours, - ) - utc_offset_minutes: int = proto.Field( - proto.INT32, - number=22, - optional=True, - ) - photos: MutableSequence[photo.Photo] = proto.RepeatedField( - proto.MESSAGE, - number=54, - message=photo.Photo, - ) - adr_format_address: str = proto.Field( - proto.STRING, - number=24, - ) - business_status: BusinessStatus = proto.Field( - proto.ENUM, - number=25, - enum=BusinessStatus, - ) - price_level: 'PriceLevel' = proto.Field( - proto.ENUM, - number=26, - enum='PriceLevel', - ) - attributions: MutableSequence[Attribution] = proto.RepeatedField( - proto.MESSAGE, - number=27, - message=Attribution, - ) - user_rating_count: int = proto.Field( - proto.INT32, - number=28, - optional=True, - ) - icon_mask_base_uri: str = proto.Field( - proto.STRING, - number=29, - ) - icon_background_color: str = proto.Field( - proto.STRING, - number=30, - ) - takeout: bool = proto.Field( - proto.BOOL, - number=33, - optional=True, - ) - delivery: bool = proto.Field( - proto.BOOL, - number=34, - optional=True, - ) - dine_in: bool = proto.Field( - proto.BOOL, - number=35, - optional=True, - ) - curbside_pickup: bool = proto.Field( - proto.BOOL, - number=36, - optional=True, - ) - reservable: bool = proto.Field( - proto.BOOL, - number=38, - optional=True, - ) - serves_breakfast: bool = proto.Field( - proto.BOOL, - number=39, - optional=True, - ) - serves_lunch: bool = proto.Field( - proto.BOOL, - number=40, - optional=True, - ) - serves_dinner: bool = proto.Field( - proto.BOOL, - number=41, - optional=True, - ) - serves_beer: bool = proto.Field( - proto.BOOL, - number=42, - optional=True, - ) - serves_wine: bool = proto.Field( - proto.BOOL, - number=43, - optional=True, - ) - serves_brunch: bool = proto.Field( - proto.BOOL, - number=44, - optional=True, - ) - serves_vegetarian_food: bool = proto.Field( - proto.BOOL, - number=45, - optional=True, - ) - current_opening_hours: OpeningHours = proto.Field( - proto.MESSAGE, - number=46, - message=OpeningHours, - ) - current_secondary_opening_hours: MutableSequence[OpeningHours] = proto.RepeatedField( - proto.MESSAGE, - number=47, - message=OpeningHours, - ) - regular_secondary_opening_hours: MutableSequence[OpeningHours] = proto.RepeatedField( - proto.MESSAGE, - number=49, - message=OpeningHours, - ) - editorial_summary: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=52, - message=localized_text_pb2.LocalizedText, - ) - outdoor_seating: bool = proto.Field( - proto.BOOL, - number=55, - optional=True, - ) - live_music: bool = proto.Field( - proto.BOOL, - number=56, - optional=True, - ) - menu_for_children: bool = proto.Field( - proto.BOOL, - number=57, - optional=True, - ) - serves_cocktails: bool = proto.Field( - proto.BOOL, - number=58, - optional=True, - ) - serves_dessert: bool = proto.Field( - proto.BOOL, - number=59, - optional=True, - ) - serves_coffee: bool = proto.Field( - proto.BOOL, - number=60, - optional=True, - ) - good_for_children: bool = proto.Field( - proto.BOOL, - number=62, - optional=True, - ) - allows_dogs: bool = proto.Field( - proto.BOOL, - number=63, - optional=True, - ) - restroom: bool = proto.Field( - proto.BOOL, - number=64, - optional=True, - ) - good_for_groups: bool = proto.Field( - proto.BOOL, - number=65, - optional=True, - ) - good_for_watching_sports: bool = proto.Field( - proto.BOOL, - number=66, - optional=True, - ) - payment_options: PaymentOptions = proto.Field( - proto.MESSAGE, - number=67, - message=PaymentOptions, - ) - parking_options: ParkingOptions = proto.Field( - proto.MESSAGE, - number=70, - message=ParkingOptions, - ) - sub_destinations: MutableSequence[SubDestination] = proto.RepeatedField( - proto.MESSAGE, - number=71, - message=SubDestination, - ) - accessibility_options: AccessibilityOptions = proto.Field( - proto.MESSAGE, - number=72, - optional=True, - message=AccessibilityOptions, - ) - fuel_options: gmp_fuel_options.FuelOptions = proto.Field( - proto.MESSAGE, - number=78, - message=gmp_fuel_options.FuelOptions, - ) - ev_charge_options: ev_charging.EVChargeOptions = proto.Field( - proto.MESSAGE, - number=79, - message=ev_charging.EVChargeOptions, - ) - generative_summary: GenerativeSummary = proto.Field( - proto.MESSAGE, - number=80, - message=GenerativeSummary, - ) - area_summary: AreaSummary = proto.Field( - proto.MESSAGE, - number=81, - message=AreaSummary, - ) - containing_places: MutableSequence[ContainingPlace] = proto.RepeatedField( - proto.MESSAGE, - number=82, - message=ContainingPlace, - ) - pure_service_area_business: bool = proto.Field( - proto.BOOL, - number=83, - optional=True, - ) - price_range: gmp_price_range.PriceRange = proto.Field( - proto.MESSAGE, - number=86, - message=gmp_price_range.PriceRange, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py deleted file mode 100644 index efd86f57ba22..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/places_service.py +++ /dev/null @@ -1,1340 +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 -from google.maps.places_v1.types import contextual_content -from google.maps.places_v1.types import ev_charging -from google.maps.places_v1.types import geometry -from google.maps.places_v1.types import place as gmp_place -from google.maps.places_v1.types import polyline as gmp_polyline -from google.maps.places_v1.types import route_modifiers as gmp_route_modifiers -from google.maps.places_v1.types import routing_preference as gmp_routing_preference -from google.maps.places_v1.types import routing_summary -from google.maps.places_v1.types import travel_mode as gmp_travel_mode -from google.type import latlng_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'RoutingParameters', - 'SearchNearbyRequest', - 'SearchNearbyResponse', - 'SearchTextRequest', - 'SearchTextResponse', - 'GetPhotoMediaRequest', - 'PhotoMedia', - 'GetPlaceRequest', - 'AutocompletePlacesRequest', - 'AutocompletePlacesResponse', - }, -) - - -class RoutingParameters(proto.Message): - r"""Parameters to configure the routing calculations to the - places in the response, both along a route (where result ranking - will be influenced) and for calculating travel times on results. - - Attributes: - origin (google.type.latlng_pb2.LatLng): - Optional. An explicit routing origin that - overrides the origin defined in the polyline. By - default, the polyline origin is used. - travel_mode (google.maps.places_v1.types.TravelMode): - Optional. The travel mode. - route_modifiers (google.maps.places_v1.types.RouteModifiers): - Optional. The route modifiers. - routing_preference (google.maps.places_v1.types.RoutingPreference): - Optional. Specifies how to compute the routing summaries. - The server attempts to use the selected routing preference - to compute the route. The traffic aware routing preference - is only available for the ``DRIVE`` or ``TWO_WHEELER`` - ``travelMode``. - """ - - origin: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=1, - message=latlng_pb2.LatLng, - ) - travel_mode: gmp_travel_mode.TravelMode = proto.Field( - proto.ENUM, - number=2, - enum=gmp_travel_mode.TravelMode, - ) - route_modifiers: gmp_route_modifiers.RouteModifiers = proto.Field( - proto.MESSAGE, - number=3, - message=gmp_route_modifiers.RouteModifiers, - ) - routing_preference: gmp_routing_preference.RoutingPreference = proto.Field( - proto.ENUM, - number=4, - enum=gmp_routing_preference.RoutingPreference, - ) - - -class SearchNearbyRequest(proto.Message): - r"""Request proto for Search Nearby. - - Attributes: - language_code (str): - Place details will be displayed with the - preferred language if available. If the language - code is unspecified or unrecognized, place - details of any language may be returned, with a - preference for English if such details exist. - - Current list of supported languages: - - https://developers.google.com/maps/faq#languagesupport. - region_code (str): - The Unicode country/region code (CLDR) of the location where - the request is coming from. This parameter is used to - display the place details, like region-specific place name, - if available. The parameter can affect results based on - applicable law. - - For more information, see - https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html. - - Note that 3-digit region codes are not currently supported. - included_types (MutableSequence[str]): - Included Place type (eg, "restaurant" or "gas_station") from - https://developers.google.com/maps/documentation/places/web-service/place-types. - - Up to 50 types from `Table - A `__ - may be specified. - - If there are any conflicting types, i.e. a type appears in - both included_types and excluded_types, an INVALID_ARGUMENT - error is returned. - - If a Place type is specified with multiple type - restrictions, only places that satisfy all of the - restrictions are returned. For example, if we have - {included_types = ["restaurant"], excluded_primary_types = - ["restaurant"]}, the returned places provide "restaurant" - related services but do not operate primarily as - "restaurants". - excluded_types (MutableSequence[str]): - Excluded Place type (eg, "restaurant" or "gas_station") from - https://developers.google.com/maps/documentation/places/web-service/place-types. - - Up to 50 types from `Table - A `__ - may be specified. - - If the client provides both included_types (e.g. restaurant) - and excluded_types (e.g. cafe), then the response should - include places that are restaurant but not cafe. The - response includes places that match at least one of the - included_types and none of the excluded_types. - - If there are any conflicting types, i.e. a type appears in - both included_types and excluded_types, an INVALID_ARGUMENT - error is returned. - - If a Place type is specified with multiple type - restrictions, only places that satisfy all of the - restrictions are returned. For example, if we have - {included_types = ["restaurant"], excluded_primary_types = - ["restaurant"]}, the returned places provide "restaurant" - related services but do not operate primarily as - "restaurants". - included_primary_types (MutableSequence[str]): - Included primary Place type (e.g. "restaurant" or - "gas_station") from - https://developers.google.com/maps/documentation/places/web-service/place-types. - A place can only have a single primary type from the - supported types table associated with it. - - Up to 50 types from `Table - A `__ - may be specified. - - If there are any conflicting primary types, i.e. a type - appears in both included_primary_types and - excluded_primary_types, an INVALID_ARGUMENT error is - returned. - - If a Place type is specified with multiple type - restrictions, only places that satisfy all of the - restrictions are returned. For example, if we have - {included_types = ["restaurant"], excluded_primary_types = - ["restaurant"]}, the returned places provide "restaurant" - related services but do not operate primarily as - "restaurants". - excluded_primary_types (MutableSequence[str]): - Excluded primary Place type (e.g. "restaurant" or - "gas_station") from - https://developers.google.com/maps/documentation/places/web-service/place-types. - - Up to 50 types from `Table - A `__ - may be specified. - - If there are any conflicting primary types, i.e. a type - appears in both included_primary_types and - excluded_primary_types, an INVALID_ARGUMENT error is - returned. - - If a Place type is specified with multiple type - restrictions, only places that satisfy all of the - restrictions are returned. For example, if we have - {included_types = ["restaurant"], excluded_primary_types = - ["restaurant"]}, the returned places provide "restaurant" - related services but do not operate primarily as - "restaurants". - max_result_count (int): - Maximum number of results to return. It must be between 1 - and 20 (default), inclusively. If the number is unset, it - falls back to the upper limit. If the number is set to - negative or exceeds the upper limit, an INVALID_ARGUMENT - error is returned. - location_restriction (google.maps.places_v1.types.SearchNearbyRequest.LocationRestriction): - Required. The region to search. - rank_preference (google.maps.places_v1.types.SearchNearbyRequest.RankPreference): - How results will be ranked in the response. - routing_parameters (google.maps.places_v1.types.RoutingParameters): - Optional. Parameters that affect the routing - to the search results. - """ - class RankPreference(proto.Enum): - r"""How results will be ranked in the response. - - Values: - RANK_PREFERENCE_UNSPECIFIED (0): - RankPreference value not set. Will use rank - by POPULARITY by default. - DISTANCE (1): - Ranks results by distance. - POPULARITY (2): - Ranks results by popularity. - """ - RANK_PREFERENCE_UNSPECIFIED = 0 - DISTANCE = 1 - POPULARITY = 2 - - class LocationRestriction(proto.Message): - r"""The region to search. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - circle (google.maps.places_v1.types.Circle): - A circle defined by center point and radius. - - This field is a member of `oneof`_ ``type``. - """ - - circle: geometry.Circle = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message=geometry.Circle, - ) - - language_code: str = proto.Field( - proto.STRING, - number=1, - ) - region_code: str = proto.Field( - proto.STRING, - number=2, - ) - included_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - excluded_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - included_primary_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - excluded_primary_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - max_result_count: int = proto.Field( - proto.INT32, - number=7, - ) - location_restriction: LocationRestriction = proto.Field( - proto.MESSAGE, - number=8, - message=LocationRestriction, - ) - rank_preference: RankPreference = proto.Field( - proto.ENUM, - number=9, - enum=RankPreference, - ) - routing_parameters: 'RoutingParameters' = proto.Field( - proto.MESSAGE, - number=10, - message='RoutingParameters', - ) - - -class SearchNearbyResponse(proto.Message): - r"""Response proto for Search Nearby. - - Attributes: - places (MutableSequence[google.maps.places_v1.types.Place]): - A list of places that meets user's - requirements like places types, number of places - and specific location restriction. - routing_summaries (MutableSequence[google.maps.places_v1.types.RoutingSummary]): - A list of routing summaries where each entry associates to - the corresponding place in the same index in the ``places`` - field. If the routing summary is not available for one of - the places, it will contain an empty entry. This list should - have as many entries as the list of places if requested. - """ - - places: MutableSequence[gmp_place.Place] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gmp_place.Place, - ) - routing_summaries: MutableSequence[routing_summary.RoutingSummary] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=routing_summary.RoutingSummary, - ) - - -class SearchTextRequest(proto.Message): - r"""Request proto for SearchText. - - Attributes: - text_query (str): - Required. The text query for textual search. - language_code (str): - Place details will be displayed with the - preferred language if available. If the language - code is unspecified or unrecognized, place - details of any language may be returned, with a - preference for English if such details exist. - - Current list of supported languages: - - https://developers.google.com/maps/faq#languagesupport. - region_code (str): - The Unicode country/region code (CLDR) of the location where - the request is coming from. This parameter is used to - display the place details, like region-specific place name, - if available. The parameter can affect results based on - applicable law. - - For more information, see - https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html. - - Note that 3-digit region codes are not currently supported. - rank_preference (google.maps.places_v1.types.SearchTextRequest.RankPreference): - How results will be ranked in the response. - included_type (str): - The requested place type. Full list of types - supported: - https://developers.google.com/maps/documentation/places/web-service/place-types. - Only support one included type. - open_now (bool): - Used to restrict the search to places that - are currently open. The default is false. - min_rating (float): - Filter out results whose average user rating is strictly - less than this limit. A valid value must be a float between - 0 and 5 (inclusively) at a 0.5 cadence i.e. [0, 0.5, 1.0, - ... , 5.0] inclusively. The input rating will round up to - the nearest 0.5(ceiling). For instance, a rating of 0.6 will - eliminate all results with a less than 1.0 rating. - max_result_count (int): - Maximum number of results to return. It must be between 1 - and 20, inclusively. The default is 20. If the number is - unset, it falls back to the upper limit. If the number is - set to negative or exceeds the upper limit, an - INVALID_ARGUMENT error is returned. - price_levels (MutableSequence[google.maps.places_v1.types.PriceLevel]): - Used to restrict the search to places that - are marked as certain price levels. Users can - choose any combinations of price levels. Default - to select all price levels. - strict_type_filtering (bool): - Used to set strict type filtering for included_type. If set - to true, only results of the same type will be returned. - Default to false. - location_bias (google.maps.places_v1.types.SearchTextRequest.LocationBias): - The region to search. This location serves as a bias which - means results around given location might be returned. - Cannot be set along with location_restriction. - location_restriction (google.maps.places_v1.types.SearchTextRequest.LocationRestriction): - The region to search. This location serves as a restriction - which means results outside given location will not be - returned. Cannot be set along with location_bias. - ev_options (google.maps.places_v1.types.SearchTextRequest.EVOptions): - Optional. Set the searchable EV options of a - place search request. - routing_parameters (google.maps.places_v1.types.RoutingParameters): - Optional. Additional parameters for routing - to results. - search_along_route_parameters (google.maps.places_v1.types.SearchTextRequest.SearchAlongRouteParameters): - Optional. Additional parameters proto for - searching along a route. - include_pure_service_area_businesses (bool): - Optional. Include pure service area businesses if the field - is set to true. Pure service area business is a business - that visits or delivers to customers directly but does not - serve customers at their business address. For example, - businesses like cleaning services or plumbers. Those - businesses do not have a physical address or location on - Google Maps. Places will not return fields including - ``location``, ``plus_code``, and other location related - fields for these businesses. - """ - class RankPreference(proto.Enum): - r"""How results will be ranked in the response. - - Values: - RANK_PREFERENCE_UNSPECIFIED (0): - For a categorical query such as "Restaurants - in New York City", RELEVANCE is the default. For - non-categorical queries such as "Mountain View, - CA" we recommend that you leave rankPreference - unset. - DISTANCE (1): - Ranks results by distance. - RELEVANCE (2): - Ranks results by relevance. Sort order - determined by normal ranking stack. - """ - RANK_PREFERENCE_UNSPECIFIED = 0 - DISTANCE = 1 - RELEVANCE = 2 - - class LocationBias(proto.Message): - r"""The region to search. This location serves as a bias which - means results around given location might be returned. - - 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: - rectangle (google.geo.type.types.Viewport): - A rectangle box defined by northeast and southwest corner. - ``rectangle.high()`` must be the northeast point of the - rectangle viewport. ``rectangle.low()`` must be the - southwest point of the rectangle viewport. - ``rectangle.low().latitude()`` cannot be greater than - ``rectangle.high().latitude()``. This will result in an - empty latitude range. A rectangle viewport cannot be wider - than 180 degrees. - - This field is a member of `oneof`_ ``type``. - circle (google.maps.places_v1.types.Circle): - A circle defined by center point and radius. - - This field is a member of `oneof`_ ``type``. - """ - - rectangle: viewport.Viewport = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message=viewport.Viewport, - ) - circle: geometry.Circle = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message=geometry.Circle, - ) - - class LocationRestriction(proto.Message): - r"""The region to search. This location serves as a restriction - which means results outside given location will not be returned. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - rectangle (google.geo.type.types.Viewport): - A rectangle box defined by northeast and southwest corner. - ``rectangle.high()`` must be the northeast point of the - rectangle viewport. ``rectangle.low()`` must be the - southwest point of the rectangle viewport. - ``rectangle.low().latitude()`` cannot be greater than - ``rectangle.high().latitude()``. This will result in an - empty latitude range. A rectangle viewport cannot be wider - than 180 degrees. - - This field is a member of `oneof`_ ``type``. - """ - - rectangle: viewport.Viewport = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message=viewport.Viewport, - ) - - class EVOptions(proto.Message): - r"""Searchable EV options of a place search request. - - Attributes: - minimum_charging_rate_kw (float): - Optional. Minimum required charging rate in - kilowatts. A place with a charging rate less - than the specified rate is filtered out. - connector_types (MutableSequence[google.maps.places_v1.types.EVConnectorType]): - Optional. The list of preferred EV connector - types. A place that does not support any of the - listed connector types is filtered out. - """ - - minimum_charging_rate_kw: float = proto.Field( - proto.DOUBLE, - number=1, - ) - connector_types: MutableSequence[ev_charging.EVConnectorType] = proto.RepeatedField( - proto.ENUM, - number=2, - enum=ev_charging.EVConnectorType, - ) - - class SearchAlongRouteParameters(proto.Message): - r"""Specifies a precalculated polyline from the `Routes - API `__ - defining the route to search. Searching along a route is similar to - using the ``locationBias`` or ``locationRestriction`` request option - to bias the search results. However, while the ``locationBias`` and - ``locationRestriction`` options let you specify a region to bias the - search results, this option lets you bias the results along a trip - route. - - Results are not guaranteed to be along the route provided, but - rather are ranked within the search area defined by the polyline - and, optionally, by the ``locationBias`` or ``locationRestriction`` - based on minimal detour times from origin to destination. The - results might be along an alternate route, especially if the - provided polyline does not define an optimal route from origin to - destination. - - Attributes: - polyline (google.maps.places_v1.types.Polyline): - Required. The route polyline. - """ - - polyline: gmp_polyline.Polyline = proto.Field( - proto.MESSAGE, - number=1, - message=gmp_polyline.Polyline, - ) - - text_query: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - region_code: str = proto.Field( - proto.STRING, - number=3, - ) - rank_preference: RankPreference = proto.Field( - proto.ENUM, - number=4, - enum=RankPreference, - ) - included_type: str = proto.Field( - proto.STRING, - number=6, - ) - open_now: bool = proto.Field( - proto.BOOL, - number=7, - ) - min_rating: float = proto.Field( - proto.DOUBLE, - number=9, - ) - max_result_count: int = proto.Field( - proto.INT32, - number=10, - ) - price_levels: MutableSequence[gmp_place.PriceLevel] = proto.RepeatedField( - proto.ENUM, - number=11, - enum=gmp_place.PriceLevel, - ) - strict_type_filtering: bool = proto.Field( - proto.BOOL, - number=12, - ) - location_bias: LocationBias = proto.Field( - proto.MESSAGE, - number=13, - message=LocationBias, - ) - location_restriction: LocationRestriction = proto.Field( - proto.MESSAGE, - number=14, - message=LocationRestriction, - ) - ev_options: EVOptions = proto.Field( - proto.MESSAGE, - number=15, - message=EVOptions, - ) - routing_parameters: 'RoutingParameters' = proto.Field( - proto.MESSAGE, - number=16, - message='RoutingParameters', - ) - search_along_route_parameters: SearchAlongRouteParameters = proto.Field( - proto.MESSAGE, - number=17, - message=SearchAlongRouteParameters, - ) - include_pure_service_area_businesses: bool = proto.Field( - proto.BOOL, - number=20, - ) - - -class SearchTextResponse(proto.Message): - r"""Response proto for SearchText. - - Attributes: - places (MutableSequence[google.maps.places_v1.types.Place]): - A list of places that meet the user's text - search criteria. - routing_summaries (MutableSequence[google.maps.places_v1.types.RoutingSummary]): - A list of routing summaries where each entry associates to - the corresponding place in the same index in the ``places`` - field. If the routing summary is not available for one of - the places, it will contain an empty entry. This list will - have as many entries as the list of places if requested. - contextual_contents (MutableSequence[google.maps.places_v1.types.ContextualContent]): - Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - A list of contextual contents where each entry associates to - the corresponding place in the same index in the places - field. The contents that are relevant to the ``text_query`` - in the request are preferred. If the contextual content is - not available for one of the places, it will return - non-contextual content. It will be empty only when the - content is unavailable for this place. This list will have - as many entries as the list of places if requested. - """ - - places: MutableSequence[gmp_place.Place] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gmp_place.Place, - ) - routing_summaries: MutableSequence[routing_summary.RoutingSummary] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=routing_summary.RoutingSummary, - ) - contextual_contents: MutableSequence[contextual_content.ContextualContent] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=contextual_content.ContextualContent, - ) - - -class GetPhotoMediaRequest(proto.Message): - r"""Request for fetching a photo of a place using a photo - resource name. - - Attributes: - name (str): - Required. The resource name of a photo media in the format: - ``places/{place_id}/photos/{photo_reference}/media``. - - The resource name of a photo as returned in a Place object's - ``photos.name`` field comes with the format - ``places/{place_id}/photos/{photo_reference}``. You need to - append ``/media`` at the end of the photo resource to get - the photo media resource name. - max_width_px (int): - Optional. Specifies the maximum desired width, in pixels, of - the image. If the image is smaller than the values - specified, the original image will be returned. If the image - is larger in either dimension, it will be scaled to match - the smaller of the two dimensions, restricted to its - original aspect ratio. Both the max_height_px and - max_width_px properties accept an integer between 1 and - 4800, inclusively. If the value is not within the allowed - range, an INVALID_ARGUMENT error will be returned. - - At least one of max_height_px or max_width_px needs to be - specified. If neither max_height_px nor max_width_px is - specified, an INVALID_ARGUMENT error will be returned. - max_height_px (int): - Optional. Specifies the maximum desired height, in pixels, - of the image. If the image is smaller than the values - specified, the original image will be returned. If the image - is larger in either dimension, it will be scaled to match - the smaller of the two dimensions, restricted to its - original aspect ratio. Both the max_height_px and - max_width_px properties accept an integer between 1 and - 4800, inclusively. If the value is not within the allowed - range, an INVALID_ARGUMENT error will be returned. - - At least one of max_height_px or max_width_px needs to be - specified. If neither max_height_px nor max_width_px is - specified, an INVALID_ARGUMENT error will be returned. - skip_http_redirect (bool): - Optional. If set, skip the default HTTP - redirect behavior and render a text format (for - example, in JSON format for HTTP use case) - response. If not set, an HTTP redirect will be - issued to redirect the call to the image media. - This option is ignored for non-HTTP requests. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - max_width_px: int = proto.Field( - proto.INT32, - number=2, - ) - max_height_px: int = proto.Field( - proto.INT32, - number=3, - ) - skip_http_redirect: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class PhotoMedia(proto.Message): - r"""A photo media from Places API. - - Attributes: - name (str): - The resource name of a photo media in the format: - ``places/{place_id}/photos/{photo_reference}/media``. - photo_uri (str): - A short-lived uri that can be used to render - the photo. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - photo_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetPlaceRequest(proto.Message): - r"""Request for fetching a Place based on its resource name, which is a - string in the ``places/{place_id}`` format. - - Attributes: - name (str): - Required. The resource name of a place, in the - ``places/{place_id}`` format. - language_code (str): - Optional. Place details will be displayed - with the preferred language if available. - - Current list of supported languages: - - https://developers.google.com/maps/faq#languagesupport. - region_code (str): - Optional. The Unicode country/region code (CLDR) of the - location where the request is coming from. This parameter is - used to display the place details, like region-specific - place name, if available. The parameter can affect results - based on applicable law. For more information, see - https://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html. - - Note that 3-digit region codes are not currently supported. - session_token (str): - Optional. A string which identifies an Autocomplete session - for billing purposes. Must be a URL and filename safe base64 - string with at most 36 ASCII characters in length. Otherwise - an INVALID_ARGUMENT error is returned. - - The session begins when the user starts typing a query, and - concludes when they select a place and a call to Place - Details or Address Validation is made. Each session can have - multiple queries, followed by one Place Details or Address - Validation request. The credentials used for each request - within a session must belong to the same Google Cloud - Console project. Once a session has concluded, the token is - no longer valid; your app must generate a fresh token for - each session. If the ``session_token`` parameter is omitted, - or if you reuse a session token, the session is charged as - if no session token was provided (each request is billed - separately). - - We recommend the following guidelines: - - - Use session tokens for all Place Autocomplete calls. - - Generate a fresh token for each session. Using a version - 4 UUID is recommended. - - Ensure that the credentials used for all Place - Autocomplete, Place Details, and Address Validation - requests within a session belong to the same Cloud - Console project. - - Be sure to pass a unique session token for each new - session. Using the same token for more than one session - will result in each request being billed individually. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - language_code: str = proto.Field( - proto.STRING, - number=2, - ) - region_code: str = proto.Field( - proto.STRING, - number=3, - ) - session_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class AutocompletePlacesRequest(proto.Message): - r"""Request proto for AutocompletePlaces. - - Attributes: - input (str): - Required. The text string on which to search. - location_bias (google.maps.places_v1.types.AutocompletePlacesRequest.LocationBias): - Optional. Bias results to a specified location. - - At most one of ``location_bias`` or ``location_restriction`` - should be set. If neither are set, the results will be - biased by IP address, meaning the IP address will be mapped - to an imprecise location and used as a biasing signal. - location_restriction (google.maps.places_v1.types.AutocompletePlacesRequest.LocationRestriction): - Optional. Restrict results to a specified location. - - At most one of ``location_bias`` or ``location_restriction`` - should be set. If neither are set, the results will be - biased by IP address, meaning the IP address will be mapped - to an imprecise location and used as a biasing signal. - included_primary_types (MutableSequence[str]): - Optional. Included primary Place type (for example, - "restaurant" or "gas_station") in Place Types - (https://developers.google.com/maps/documentation/places/web-service/place-types), - or only ``(regions)``, or only ``(cities)``. A Place is only - returned if its primary type is included in this list. Up to - 5 values can be specified. If no types are specified, all - Place types are returned. - included_region_codes (MutableSequence[str]): - Optional. Only include results in the specified regions, - specified as up to 15 CLDR two-character region codes. An - empty set will not restrict the results. If both - ``location_restriction`` and ``included_region_codes`` are - set, the results will be located in the area of - intersection. - language_code (str): - Optional. The language in which to return results. Defaults - to en-US. The results may be in mixed languages if the - language used in ``input`` is different from - ``language_code`` or if the returned Place does not have a - translation from the local language to ``language_code``. - region_code (str): - Optional. The region code, specified as a CLDR two-character - region code. This affects address formatting, result - ranking, and may influence what results are returned. This - does not restrict results to the specified region. To - restrict results to a region, use - ``region_code_restriction``. - origin (google.type.latlng_pb2.LatLng): - Optional. The origin point from which to calculate geodesic - distance to the destination (returned as - ``distance_meters``). If this value is omitted, geodesic - distance will not be returned. - input_offset (int): - Optional. A zero-based Unicode character offset of ``input`` - indicating the cursor position in ``input``. The cursor - position may influence what predictions are returned. - - If empty, defaults to the length of ``input``. - include_query_predictions (bool): - Optional. If true, the response will include - both Place and query predictions. Otherwise the - response will only return Place predictions. - session_token (str): - Optional. A string which identifies an Autocomplete session - for billing purposes. Must be a URL and filename safe base64 - string with at most 36 ASCII characters in length. Otherwise - an INVALID_ARGUMENT error is returned. - - The session begins when the user starts typing a query, and - concludes when they select a place and a call to Place - Details or Address Validation is made. Each session can have - multiple queries, followed by one Place Details or Address - Validation request. The credentials used for each request - within a session must belong to the same Google Cloud - Console project. Once a session has concluded, the token is - no longer valid; your app must generate a fresh token for - each session. If the ``session_token`` parameter is omitted, - or if you reuse a session token, the session is charged as - if no session token was provided (each request is billed - separately). - - We recommend the following guidelines: - - - Use session tokens for all Place Autocomplete calls. - - Generate a fresh token for each session. Using a version - 4 UUID is recommended. - - Ensure that the credentials used for all Place - Autocomplete, Place Details, and Address Validation - requests within a session belong to the same Cloud - Console project. - - Be sure to pass a unique session token for each new - session. Using the same token for more than one session - will result in each request being billed individually. - include_pure_service_area_businesses (bool): - Optional. Include pure service area businesses if the field - is set to true. Pure service area business is a business - that visits or delivers to customers directly but does not - serve customers at their business address. For example, - businesses like cleaning services or plumbers. Those - businesses do not have a physical address or location on - Google Maps. Places will not return fields including - ``location``, ``plus_code``, and other location related - fields for these businesses. - """ - - class LocationBias(proto.Message): - r"""The region to search. The results may be biased around the - specified region. - - 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: - rectangle (google.geo.type.types.Viewport): - A viewport defined by a northeast and a - southwest corner. - - This field is a member of `oneof`_ ``type``. - circle (google.maps.places_v1.types.Circle): - A circle defined by a center point and - radius. - - This field is a member of `oneof`_ ``type``. - """ - - rectangle: viewport.Viewport = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message=viewport.Viewport, - ) - circle: geometry.Circle = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message=geometry.Circle, - ) - - class LocationRestriction(proto.Message): - r"""The region to search. The results will be restricted to the - specified region. - - 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: - rectangle (google.geo.type.types.Viewport): - A viewport defined by a northeast and a - southwest corner. - - This field is a member of `oneof`_ ``type``. - circle (google.maps.places_v1.types.Circle): - A circle defined by a center point and - radius. - - This field is a member of `oneof`_ ``type``. - """ - - rectangle: viewport.Viewport = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message=viewport.Viewport, - ) - circle: geometry.Circle = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message=geometry.Circle, - ) - - input: str = proto.Field( - proto.STRING, - number=1, - ) - location_bias: LocationBias = proto.Field( - proto.MESSAGE, - number=2, - message=LocationBias, - ) - location_restriction: LocationRestriction = proto.Field( - proto.MESSAGE, - number=3, - message=LocationRestriction, - ) - included_primary_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - included_region_codes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - language_code: str = proto.Field( - proto.STRING, - number=6, - ) - region_code: str = proto.Field( - proto.STRING, - number=7, - ) - origin: latlng_pb2.LatLng = proto.Field( - proto.MESSAGE, - number=8, - message=latlng_pb2.LatLng, - ) - input_offset: int = proto.Field( - proto.INT32, - number=9, - ) - include_query_predictions: bool = proto.Field( - proto.BOOL, - number=10, - ) - session_token: str = proto.Field( - proto.STRING, - number=11, - ) - include_pure_service_area_businesses: bool = proto.Field( - proto.BOOL, - number=12, - ) - - -class AutocompletePlacesResponse(proto.Message): - r"""Response proto for AutocompletePlaces. - - Attributes: - suggestions (MutableSequence[google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion]): - Contains a list of suggestions, ordered in - descending order of relevance. - """ - - class Suggestion(proto.Message): - r"""An Autocomplete suggestion result. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - place_prediction (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.PlacePrediction): - A prediction for a Place. - - This field is a member of `oneof`_ ``kind``. - query_prediction (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.QueryPrediction): - A prediction for a query. - - This field is a member of `oneof`_ ``kind``. - """ - - class StringRange(proto.Message): - r"""Identifies a substring within a given text. - - Attributes: - start_offset (int): - Zero-based offset of the first Unicode - character of the string (inclusive). - end_offset (int): - Zero-based offset of the last Unicode - character (exclusive). - """ - - start_offset: int = proto.Field( - proto.INT32, - number=1, - ) - end_offset: int = proto.Field( - proto.INT32, - number=2, - ) - - class FormattableText(proto.Message): - r"""Text representing a Place or query prediction. The text may - be used as is or formatted. - - Attributes: - text (str): - Text that may be used as is or formatted with ``matches``. - matches (MutableSequence[google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.StringRange]): - A list of string ranges identifying where the input request - matched in ``text``. The ranges can be used to format - specific parts of ``text``. The substrings may not be exact - matches of ``input`` if the matching was determined by - criteria other than string matching (for example, spell - corrections or transliterations). - - These values are Unicode character offsets of ``text``. The - ranges are guaranteed to be ordered in increasing offset - values. - """ - - text: str = proto.Field( - proto.STRING, - number=1, - ) - matches: MutableSequence['AutocompletePlacesResponse.Suggestion.StringRange'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AutocompletePlacesResponse.Suggestion.StringRange', - ) - - class StructuredFormat(proto.Message): - r"""Contains a breakdown of a Place or query prediction into main - text and secondary text. - - For Place predictions, the main text contains the specific name - of the Place. For query predictions, the main text contains the - query. - - The secondary text contains additional disambiguating features - (such as a city or region) to further identify the Place or - refine the query. - - Attributes: - main_text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): - Represents the name of the Place or query. - secondary_text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): - Represents additional disambiguating features - (such as a city or region) to further identify - the Place or refine the query. - """ - - main_text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( - proto.MESSAGE, - number=1, - message='AutocompletePlacesResponse.Suggestion.FormattableText', - ) - secondary_text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( - proto.MESSAGE, - number=2, - message='AutocompletePlacesResponse.Suggestion.FormattableText', - ) - - class PlacePrediction(proto.Message): - r"""Prediction results for a Place Autocomplete prediction. - - Attributes: - place (str): - The resource name of the suggested Place. - This name can be used in other APIs that accept - Place names. - place_id (str): - The unique identifier of the suggested Place. - This identifier can be used in other APIs that - accept Place IDs. - text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): - Contains the human-readable name for the returned result. - For establishment results, this is usually the business name - and address. - - ``text`` is recommended for developers who wish to show a - single UI element. Developers who wish to show two separate, - but related, UI elements may want to use - ``structured_format`` instead. They are two different ways - to represent a Place prediction. Users should not try to - parse ``structured_format`` into ``text`` or vice versa. - - This text may be different from the ``display_name`` - returned by GetPlace. - - May be in mixed languages if the request ``input`` and - ``language_code`` are in different languages or if the Place - does not have a translation from the local language to - ``language_code``. - structured_format (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.StructuredFormat): - A breakdown of the Place prediction into main text - containing the name of the Place and secondary text - containing additional disambiguating features (such as a - city or region). - - ``structured_format`` is recommended for developers who wish - to show two separate, but related, UI elements. Developers - who wish to show a single UI element may want to use - ``text`` instead. They are two different ways to represent a - Place prediction. Users should not try to parse - ``structured_format`` into ``text`` or vice versa. - types (MutableSequence[str]): - List of types that apply to this Place from - Table A or Table B in - https://developers.google.com/maps/documentation/places/web-service/place-types. - - A type is a categorization of a Place. Places - with shared types will share similar - characteristics. - distance_meters (int): - The length of the geodesic in meters from ``origin`` if - ``origin`` is specified. Certain predictions such as routes - may not populate this field. - """ - - place: str = proto.Field( - proto.STRING, - number=1, - ) - place_id: str = proto.Field( - proto.STRING, - number=2, - ) - text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( - proto.MESSAGE, - number=3, - message='AutocompletePlacesResponse.Suggestion.FormattableText', - ) - structured_format: 'AutocompletePlacesResponse.Suggestion.StructuredFormat' = proto.Field( - proto.MESSAGE, - number=4, - message='AutocompletePlacesResponse.Suggestion.StructuredFormat', - ) - types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - distance_meters: int = proto.Field( - proto.INT32, - number=6, - ) - - class QueryPrediction(proto.Message): - r"""Prediction results for a Query Autocomplete prediction. - - Attributes: - text (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.FormattableText): - The predicted text. This text does not represent a Place, - but rather a text query that could be used in a search - endpoint (for example, Text Search). - - ``text`` is recommended for developers who wish to show a - single UI element. Developers who wish to show two separate, - but related, UI elements may want to use - ``structured_format`` instead. They are two different ways - to represent a query prediction. Users should not try to - parse ``structured_format`` into ``text`` or vice versa. - - May be in mixed languages if the request ``input`` and - ``language_code`` are in different languages or if part of - the query does not have a translation from the local - language to ``language_code``. - structured_format (google.maps.places_v1.types.AutocompletePlacesResponse.Suggestion.StructuredFormat): - A breakdown of the query prediction into main text - containing the query and secondary text containing - additional disambiguating features (such as a city or - region). - - ``structured_format`` is recommended for developers who wish - to show two separate, but related, UI elements. Developers - who wish to show a single UI element may want to use - ``text`` instead. They are two different ways to represent a - query prediction. Users should not try to parse - ``structured_format`` into ``text`` or vice versa. - """ - - text: 'AutocompletePlacesResponse.Suggestion.FormattableText' = proto.Field( - proto.MESSAGE, - number=1, - message='AutocompletePlacesResponse.Suggestion.FormattableText', - ) - structured_format: 'AutocompletePlacesResponse.Suggestion.StructuredFormat' = proto.Field( - proto.MESSAGE, - number=2, - message='AutocompletePlacesResponse.Suggestion.StructuredFormat', - ) - - place_prediction: 'AutocompletePlacesResponse.Suggestion.PlacePrediction' = proto.Field( - proto.MESSAGE, - number=1, - oneof='kind', - message='AutocompletePlacesResponse.Suggestion.PlacePrediction', - ) - query_prediction: 'AutocompletePlacesResponse.Suggestion.QueryPrediction' = proto.Field( - proto.MESSAGE, - number=2, - oneof='kind', - message='AutocompletePlacesResponse.Suggestion.QueryPrediction', - ) - - suggestions: MutableSequence[Suggestion] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Suggestion, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py deleted file mode 100644 index 6c0ee26282c7..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/polyline.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'Polyline', - }, -) - - -class Polyline(proto.Message): - r"""A route polyline. Only supports an `encoded - polyline `__, - which can be passed as a string and includes compression with - minimal lossiness. This is the Routes API default output. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - encoded_polyline (str): - An `encoded - polyline `__, - as returned by the `Routes API by - default `__. - See the - `encoder `__ - and - `decoder `__ - tools. - - This field is a member of `oneof`_ ``polyline_type``. - """ - - encoded_polyline: str = proto.Field( - proto.STRING, - number=1, - oneof='polyline_type', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.py deleted file mode 100644 index 597eaba8af64..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/price_range.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.type import money_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'PriceRange', - }, -) - - -class PriceRange(proto.Message): - r"""The price range associated with a Place. ``end_price`` could be - unset, which indicates a range without upper bound (e.g. "More than - $100"). - - Attributes: - start_price (google.type.money_pb2.Money): - The low end of the price range (inclusive). - Price should be at or above this amount. - end_price (google.type.money_pb2.Money): - The high end of the price range (exclusive). - Price should be lower than this amount. - """ - - start_price: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=1, - message=money_pb2.Money, - ) - end_price: money_pb2.Money = proto.Field( - proto.MESSAGE, - number=2, - message=money_pb2.Money, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py deleted file mode 100644 index 5dee1df6fa73..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/reference.py +++ /dev/null @@ -1,60 +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.places_v1.types import review - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'References', - }, -) - - -class References(proto.Message): - r"""Experimental: See - https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative - for more details. - - Reference that the generative content is related to. - - Attributes: - reviews (MutableSequence[google.maps.places_v1.types.Review]): - Reviews that serve as references. - places (MutableSequence[str]): - The list of resource names of the referenced - places. This name can be used in other APIs that - accept Place resource names. - """ - - reviews: MutableSequence[review.Review] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=review.Review, - ) - places: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.py deleted file mode 100644 index 96e161266398..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/review.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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.maps.places_v1.types import attribution -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'Review', - }, -) - - -class Review(proto.Message): - r"""Information about a review of a place. - - Attributes: - name (str): - A reference representing this place review which may be used - to look up this place review again (also called the API - "resource" name: ``places/{place_id}/reviews/{review}``). - relative_publish_time_description (str): - A string of formatted recent time, expressing - the review time relative to the current time in - a form appropriate for the language and country. - text (google.type.localized_text_pb2.LocalizedText): - The localized text of the review. - original_text (google.type.localized_text_pb2.LocalizedText): - The review text in its original language. - rating (float): - A number between 1.0 and 5.0, also called the - number of stars. - author_attribution (google.maps.places_v1.types.AuthorAttribution): - This review's author. - publish_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp for the review. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - relative_publish_time_description: str = proto.Field( - proto.STRING, - number=2, - ) - text: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=9, - message=localized_text_pb2.LocalizedText, - ) - original_text: localized_text_pb2.LocalizedText = proto.Field( - proto.MESSAGE, - number=12, - message=localized_text_pb2.LocalizedText, - ) - rating: float = proto.Field( - proto.DOUBLE, - number=7, - ) - author_attribution: attribution.AuthorAttribution = proto.Field( - proto.MESSAGE, - number=13, - message=attribution.AuthorAttribution, - ) - publish_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=14, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py deleted file mode 100644 index 8ad10991ebd9..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/route_modifiers.py +++ /dev/null @@ -1,76 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'RouteModifiers', - }, -) - - -class RouteModifiers(proto.Message): - r"""Encapsulates a set of optional conditions to satisfy when - calculating the routes. - - Attributes: - avoid_tolls (bool): - Optional. When set to true, avoids toll roads where - reasonable, giving preference to routes not containing toll - roads. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - [``TravelMode``][google.maps.places.v1.TravelMode]. - avoid_highways (bool): - Optional. When set to true, avoids highways where - reasonable, giving preference to routes not containing - highways. Applies only to the ``DRIVE`` and ``TWO_WHEELER`` - [``TravelMode``][google.maps.places.v1.TravelMode]. - avoid_ferries (bool): - Optional. When set to true, avoids ferries where reasonable, - giving preference to routes not containing ferries. Applies - only to the ``DRIVE`` and ``TWO_WHEELER`` - [``TravelMode``][google.maps.places.v1.TravelMode]. - avoid_indoor (bool): - Optional. When set to true, avoids navigating indoors where - reasonable, giving preference to routes not containing - indoor navigation. Applies only to the ``WALK`` - [``TravelMode``][google.maps.places.v1.TravelMode]. - """ - - avoid_tolls: bool = proto.Field( - proto.BOOL, - number=1, - ) - avoid_highways: bool = proto.Field( - proto.BOOL, - number=2, - ) - avoid_ferries: bool = proto.Field( - proto.BOOL, - number=3, - ) - avoid_indoor: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py deleted file mode 100644 index 56db65ad4e2a..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_preference.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'RoutingPreference', - }, -) - - -class RoutingPreference(proto.Enum): - r"""A set of values that specify factors to take into - consideration when calculating the route. - - Values: - ROUTING_PREFERENCE_UNSPECIFIED (0): - No routing preference specified. Default to - ``TRAFFIC_UNAWARE``. - TRAFFIC_UNAWARE (1): - Computes routes without taking live traffic conditions into - consideration. Suitable when traffic conditions don't matter - or are not applicable. Using this value produces the lowest - latency. Note: For - [``TravelMode``][google.maps.places.v1.TravelMode] ``DRIVE`` - and ``TWO_WHEELER``, the route and duration chosen are based - on road network and average time-independent traffic - conditions, not current road conditions. Consequently, - routes may include roads that are temporarily closed. - Results for a given request may vary over time due to - changes in the road network, updated average traffic - conditions, and the distributed nature of the service. - Results may also vary between nearly-equivalent routes at - any time or frequency. - TRAFFIC_AWARE (2): - Calculates routes taking live traffic conditions into - consideration. In contrast to ``TRAFFIC_AWARE_OPTIMAL``, - some optimizations are applied to significantly reduce - latency. - TRAFFIC_AWARE_OPTIMAL (3): - Calculates the routes taking live traffic - conditions into consideration, without applying - most performance optimizations. Using this value - produces the highest latency. - """ - ROUTING_PREFERENCE_UNSPECIFIED = 0 - TRAFFIC_UNAWARE = 1 - TRAFFIC_AWARE = 2 - TRAFFIC_AWARE_OPTIMAL = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py deleted file mode 100644 index 741e004f7541..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/routing_summary.py +++ /dev/null @@ -1,95 +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 duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'RoutingSummary', - }, -) - - -class RoutingSummary(proto.Message): - r"""The duration and distance from the routing origin to a place in the - response, and a second leg from that place to the destination, if - requested. **Note:** Adding ``routingSummaries`` in the field mask - without also including either the ``routingParameters.origin`` - parameter or the - ``searchAlongRouteParameters.polyline.encodedPolyline`` parameter in - the request causes an error. - - Attributes: - legs (MutableSequence[google.maps.places_v1.types.RoutingSummary.Leg]): - The legs of the trip. - - When you calculate travel duration and distance from a set - origin, ``legs`` contains a single leg containing the - duration and distance from the origin to the destination. - When you do a search along route, ``legs`` contains two - legs: one from the origin to place, and one from the place - to the destination. - directions_uri (str): - A link to show directions on Google Maps using the waypoints - from the given routing summary. The route generated by this - link is not guaranteed to be the same as the route used to - generate the routing summary. The link uses information - provided in the request, from fields including - ``routingParameters`` and ``searchAlongRouteParameters`` - when applicable, to generate the directions link. - """ - - class Leg(proto.Message): - r"""A leg is a single portion of a journey from one location to - another. - - Attributes: - duration (google.protobuf.duration_pb2.Duration): - The time it takes to complete this leg of the - trip. - distance_meters (int): - The distance of this leg of the trip. - """ - - duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - distance_meters: int = proto.Field( - proto.INT32, - number=2, - ) - - legs: MutableSequence[Leg] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=Leg, - ) - directions_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py b/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py deleted file mode 100644 index 270ba1245921..000000000000 --- a/owl-bot-staging/google-maps-places/v1/google/maps/places_v1/types/travel_mode.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.maps.places.v1', - manifest={ - 'TravelMode', - }, -) - - -class TravelMode(proto.Enum): - r"""Travel mode options. These options map to what `Routes API - offers `__. - - Values: - TRAVEL_MODE_UNSPECIFIED (0): - No travel mode specified. Defaults to ``DRIVE``. - DRIVE (1): - Travel by passenger car. - BICYCLE (2): - Travel by bicycle. Not supported with - ``search_along_route_parameters``. - WALK (3): - Travel by walking. Not supported with - ``search_along_route_parameters``. - TWO_WHEELER (4): - Motorized two wheeled vehicles of all kinds such as scooters - and motorcycles. Note that this is distinct from the - ``BICYCLE`` travel mode which covers human-powered - transport. Not supported with - ``search_along_route_parameters``. Only supported in those - countries listed at `Countries and regions supported for - two-wheeled - vehicles `__. - """ - TRAVEL_MODE_UNSPECIFIED = 0 - DRIVE = 1 - BICYCLE = 2 - WALK = 3 - TWO_WHEELER = 4 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-maps-places/v1/mypy.ini b/owl-bot-staging/google-maps-places/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/noxfile.py b/owl-bot-staging/google-maps-places/v1/noxfile.py deleted file mode 100644 index ef3066e9ef06..000000000000 --- a/owl-bot-staging/google-maps-places/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-maps-places' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/places_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/maps/places_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-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_async.py deleted file mode 100644 index abd008c9c11a..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_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 AutocompletePlaces -# 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-places - - -# [START places_v1_generated_Places_AutocompletePlaces_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 places_v1 - - -async def sample_autocomplete_places(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.AutocompletePlacesRequest( - input="input_value", - ) - - # Make the request - response = await client.autocomplete_places(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_AutocompletePlaces_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_sync.py deleted file mode 100644 index cf942b606419..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_autocomplete_places_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 AutocompletePlaces -# 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-places - - -# [START places_v1_generated_Places_AutocompletePlaces_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 places_v1 - - -def sample_autocomplete_places(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.AutocompletePlacesRequest( - input="input_value", - ) - - # Make the request - response = client.autocomplete_places(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_AutocompletePlaces_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_async.py deleted file mode 100644 index 45461ad3fabb..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_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 GetPhotoMedia -# 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-places - - -# [START places_v1_generated_Places_GetPhotoMedia_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 places_v1 - - -async def sample_get_photo_media(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.GetPhotoMediaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_photo_media(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_GetPhotoMedia_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_sync.py deleted file mode 100644 index 3f76e66b03dc..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_photo_media_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 GetPhotoMedia -# 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-places - - -# [START places_v1_generated_Places_GetPhotoMedia_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 places_v1 - - -def sample_get_photo_media(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.GetPhotoMediaRequest( - name="name_value", - ) - - # Make the request - response = client.get_photo_media(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_GetPhotoMedia_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_async.py deleted file mode 100644 index 405094ecdc49..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_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 GetPlace -# 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-places - - -# [START places_v1_generated_Places_GetPlace_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 places_v1 - - -async def sample_get_place(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.GetPlaceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_place(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_GetPlace_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_sync.py deleted file mode 100644 index 8f06103be971..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_get_place_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 GetPlace -# 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-places - - -# [START places_v1_generated_Places_GetPlace_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 places_v1 - - -def sample_get_place(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.GetPlaceRequest( - name="name_value", - ) - - # Make the request - response = client.get_place(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_GetPlace_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py deleted file mode 100644 index ea224ebeb855..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_async.py +++ /dev/null @@ -1,55 +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 SearchNearby -# 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-places - - -# [START places_v1_generated_Places_SearchNearby_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 places_v1 - - -async def sample_search_nearby(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - location_restriction = places_v1.LocationRestriction() - location_restriction.circle.radius = 0.648 - - request = places_v1.SearchNearbyRequest( - location_restriction=location_restriction, - ) - - # Make the request - response = await client.search_nearby(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_SearchNearby_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py deleted file mode 100644 index 777bbc051f7f..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_nearby_sync.py +++ /dev/null @@ -1,55 +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 SearchNearby -# 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-places - - -# [START places_v1_generated_Places_SearchNearby_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 places_v1 - - -def sample_search_nearby(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - location_restriction = places_v1.LocationRestriction() - location_restriction.circle.radius = 0.648 - - request = places_v1.SearchNearbyRequest( - location_restriction=location_restriction, - ) - - # Make the request - response = client.search_nearby(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_SearchNearby_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_async.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_async.py deleted file mode 100644 index 5f4b02670755..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_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 SearchText -# 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-places - - -# [START places_v1_generated_Places_SearchText_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 places_v1 - - -async def sample_search_text(): - # Create a client - client = places_v1.PlacesAsyncClient() - - # Initialize request argument(s) - request = places_v1.SearchTextRequest( - text_query="text_query_value", - ) - - # Make the request - response = await client.search_text(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_SearchText_async] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_sync.py b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_sync.py deleted file mode 100644 index fc156bc302cd..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/places_v1_generated_places_search_text_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 SearchText -# 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-places - - -# [START places_v1_generated_Places_SearchText_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 places_v1 - - -def sample_search_text(): - # Create a client - client = places_v1.PlacesClient() - - # Initialize request argument(s) - request = places_v1.SearchTextRequest( - text_query="text_query_value", - ) - - # Make the request - response = client.search_text(request=request) - - # Handle the response - print(response) - -# [END places_v1_generated_Places_SearchText_sync] diff --git a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json b/owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json deleted file mode 100644 index bea29a42b294..000000000000 --- a/owl-bot-staging/google-maps-places/v1/samples/generated_samples/snippet_metadata_google.maps.places.v1.json +++ /dev/null @@ -1,796 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.maps.places.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-maps-places", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.places_v1.PlacesAsyncClient", - "shortName": "PlacesAsyncClient" - }, - "fullName": "google.maps.places_v1.PlacesAsyncClient.autocomplete_places", - "method": { - "fullName": "google.maps.places.v1.Places.AutocompletePlaces", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "AutocompletePlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.AutocompletePlacesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.AutocompletePlacesResponse", - "shortName": "autocomplete_places" - }, - "description": "Sample for AutocompletePlaces", - "file": "places_v1_generated_places_autocomplete_places_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_AutocompletePlaces_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": "places_v1_generated_places_autocomplete_places_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.places_v1.PlacesClient", - "shortName": "PlacesClient" - }, - "fullName": "google.maps.places_v1.PlacesClient.autocomplete_places", - "method": { - "fullName": "google.maps.places.v1.Places.AutocompletePlaces", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "AutocompletePlaces" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.AutocompletePlacesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.AutocompletePlacesResponse", - "shortName": "autocomplete_places" - }, - "description": "Sample for AutocompletePlaces", - "file": "places_v1_generated_places_autocomplete_places_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_AutocompletePlaces_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": "places_v1_generated_places_autocomplete_places_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.places_v1.PlacesAsyncClient", - "shortName": "PlacesAsyncClient" - }, - "fullName": "google.maps.places_v1.PlacesAsyncClient.get_photo_media", - "method": { - "fullName": "google.maps.places.v1.Places.GetPhotoMedia", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "GetPhotoMedia" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.GetPhotoMediaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.PhotoMedia", - "shortName": "get_photo_media" - }, - "description": "Sample for GetPhotoMedia", - "file": "places_v1_generated_places_get_photo_media_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_GetPhotoMedia_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": "places_v1_generated_places_get_photo_media_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.places_v1.PlacesClient", - "shortName": "PlacesClient" - }, - "fullName": "google.maps.places_v1.PlacesClient.get_photo_media", - "method": { - "fullName": "google.maps.places.v1.Places.GetPhotoMedia", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "GetPhotoMedia" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.GetPhotoMediaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.PhotoMedia", - "shortName": "get_photo_media" - }, - "description": "Sample for GetPhotoMedia", - "file": "places_v1_generated_places_get_photo_media_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_GetPhotoMedia_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": "places_v1_generated_places_get_photo_media_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.places_v1.PlacesAsyncClient", - "shortName": "PlacesAsyncClient" - }, - "fullName": "google.maps.places_v1.PlacesAsyncClient.get_place", - "method": { - "fullName": "google.maps.places.v1.Places.GetPlace", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "GetPlace" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.GetPlaceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.Place", - "shortName": "get_place" - }, - "description": "Sample for GetPlace", - "file": "places_v1_generated_places_get_place_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_GetPlace_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": "places_v1_generated_places_get_place_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.places_v1.PlacesClient", - "shortName": "PlacesClient" - }, - "fullName": "google.maps.places_v1.PlacesClient.get_place", - "method": { - "fullName": "google.maps.places.v1.Places.GetPlace", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "GetPlace" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.GetPlaceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.Place", - "shortName": "get_place" - }, - "description": "Sample for GetPlace", - "file": "places_v1_generated_places_get_place_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_GetPlace_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": "places_v1_generated_places_get_place_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.places_v1.PlacesAsyncClient", - "shortName": "PlacesAsyncClient" - }, - "fullName": "google.maps.places_v1.PlacesAsyncClient.search_nearby", - "method": { - "fullName": "google.maps.places.v1.Places.SearchNearby", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "SearchNearby" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.SearchNearbyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.SearchNearbyResponse", - "shortName": "search_nearby" - }, - "description": "Sample for SearchNearby", - "file": "places_v1_generated_places_search_nearby_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_SearchNearby_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "places_v1_generated_places_search_nearby_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.places_v1.PlacesClient", - "shortName": "PlacesClient" - }, - "fullName": "google.maps.places_v1.PlacesClient.search_nearby", - "method": { - "fullName": "google.maps.places.v1.Places.SearchNearby", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "SearchNearby" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.SearchNearbyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.SearchNearbyResponse", - "shortName": "search_nearby" - }, - "description": "Sample for SearchNearby", - "file": "places_v1_generated_places_search_nearby_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_SearchNearby_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "places_v1_generated_places_search_nearby_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.places_v1.PlacesAsyncClient", - "shortName": "PlacesAsyncClient" - }, - "fullName": "google.maps.places_v1.PlacesAsyncClient.search_text", - "method": { - "fullName": "google.maps.places.v1.Places.SearchText", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "SearchText" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.SearchTextRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.SearchTextResponse", - "shortName": "search_text" - }, - "description": "Sample for SearchText", - "file": "places_v1_generated_places_search_text_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_SearchText_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": "places_v1_generated_places_search_text_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.places_v1.PlacesClient", - "shortName": "PlacesClient" - }, - "fullName": "google.maps.places_v1.PlacesClient.search_text", - "method": { - "fullName": "google.maps.places.v1.Places.SearchText", - "service": { - "fullName": "google.maps.places.v1.Places", - "shortName": "Places" - }, - "shortName": "SearchText" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.places_v1.types.SearchTextRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.maps.places_v1.types.SearchTextResponse", - "shortName": "search_text" - }, - "description": "Sample for SearchText", - "file": "places_v1_generated_places_search_text_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "places_v1_generated_Places_SearchText_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": "places_v1_generated_places_search_text_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py b/owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py deleted file mode 100644 index c1c498261a9a..000000000000 --- a/owl-bot-staging/google-maps-places/v1/scripts/fixup_places_v1_keywords.py +++ /dev/null @@ -1,180 +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 placesCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'autocomplete_places': ('input', 'location_bias', 'location_restriction', 'included_primary_types', 'included_region_codes', 'language_code', 'region_code', 'origin', 'input_offset', 'include_query_predictions', 'session_token', 'include_pure_service_area_businesses', ), - 'get_photo_media': ('name', 'max_width_px', 'max_height_px', 'skip_http_redirect', ), - 'get_place': ('name', 'language_code', 'region_code', 'session_token', ), - 'search_nearby': ('location_restriction', 'language_code', 'region_code', 'included_types', 'excluded_types', 'included_primary_types', 'excluded_primary_types', 'max_result_count', 'rank_preference', 'routing_parameters', ), - 'search_text': ('text_query', 'language_code', 'region_code', 'rank_preference', 'included_type', 'open_now', 'min_rating', 'max_result_count', 'price_levels', 'strict_type_filtering', 'location_bias', 'location_restriction', 'ev_options', 'routing_parameters', 'search_along_route_parameters', 'include_pure_service_area_businesses', ), - } - - 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=placesCallTransformer(), -): - """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 places 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-places/v1/setup.py b/owl-bot-staging/google-maps-places/v1/setup.py deleted file mode 100644 index 90538f3b071c..000000000000 --- a/owl-bot-staging/google-maps-places/v1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-maps-places' - - -description = "Google Maps Places API client library" - -version = None - -with open(os.path.join(package_root, 'google/maps/places/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "google-geo-type >= 0.1.0, <1.0.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-places" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.10.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.11.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.12.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -google-geo-type diff --git a/owl-bot-staging/google-maps-places/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.7.txt deleted file mode 100644 index 277853c664a0..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.8.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-maps-places/v1/testing/constraints-3.9.txt deleted file mode 100644 index 2214a366a259..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/tests/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/tests/unit/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-places/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-places/v1/tests/unit/gapic/places_v1/__init__.py b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_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-places/v1/tests/unit/gapic/places_v1/test_places.py b/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/test_places.py deleted file mode 100644 index 348476f125ff..000000000000 --- a/owl-bot-staging/google-maps-places/v1/tests/unit/gapic/places_v1/test_places.py +++ /dev/null @@ -1,4471 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.geo.type.types import viewport -from google.maps.places_v1.services.places import PlacesAsyncClient -from google.maps.places_v1.services.places import PlacesClient -from google.maps.places_v1.services.places import transports -from google.maps.places_v1.types import contextual_content -from google.maps.places_v1.types import ev_charging -from google.maps.places_v1.types import fuel_options -from google.maps.places_v1.types import geometry -from google.maps.places_v1.types import photo -from google.maps.places_v1.types import place -from google.maps.places_v1.types import places_service -from google.maps.places_v1.types import polyline -from google.maps.places_v1.types import price_range -from google.maps.places_v1.types import review -from google.maps.places_v1.types import route_modifiers -from google.maps.places_v1.types import routing_preference -from google.maps.places_v1.types import routing_summary -from google.maps.places_v1.types import travel_mode -from google.oauth2 import service_account -from google.type import latlng_pb2 # type: ignore -from google.type import localized_text_pb2 # type: ignore -import google.auth - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert PlacesClient._get_default_mtls_endpoint(None) is None - assert PlacesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert PlacesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert PlacesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert PlacesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert PlacesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert PlacesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert PlacesClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert PlacesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - PlacesClient._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 PlacesClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert PlacesClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert PlacesClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - PlacesClient._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 PlacesClient._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 PlacesClient._get_client_cert_source(None, False) is None - assert PlacesClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert PlacesClient._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 PlacesClient._get_client_cert_source(None, True) is mock_default_cert_source - assert PlacesClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) -@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = PlacesClient._DEFAULT_UNIVERSE - default_endpoint = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert PlacesClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert PlacesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == PlacesClient.DEFAULT_MTLS_ENDPOINT - assert PlacesClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert PlacesClient._get_api_endpoint(None, None, default_universe, "always") == PlacesClient.DEFAULT_MTLS_ENDPOINT - assert PlacesClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == PlacesClient.DEFAULT_MTLS_ENDPOINT - assert PlacesClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert PlacesClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - PlacesClient._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 PlacesClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert PlacesClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert PlacesClient._get_universe_domain(None, None) == PlacesClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - PlacesClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (PlacesClient, "grpc"), - (PlacesAsyncClient, "grpc_asyncio"), - (PlacesClient, "rest"), -]) -def test_places_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 == ( - 'places.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://places.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.PlacesGrpcTransport, "grpc"), - (transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.PlacesRestTransport, "rest"), -]) -def test_places_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", [ - (PlacesClient, "grpc"), - (PlacesAsyncClient, "grpc_asyncio"), - (PlacesClient, "rest"), -]) -def test_places_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 == ( - 'places.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://places.googleapis.com' - ) - - -def test_places_client_get_transport_class(): - transport = PlacesClient.get_transport_class() - available_transports = [ - transports.PlacesGrpcTransport, - transports.PlacesRestTransport, - ] - assert transport in available_transports - - transport = PlacesClient.get_transport_class("grpc") - assert transport == transports.PlacesGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (PlacesClient, transports.PlacesGrpcTransport, "grpc"), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio"), - (PlacesClient, transports.PlacesRestTransport, "rest"), -]) -@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) -@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) -def test_places_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(PlacesClient, '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(PlacesClient, '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", [ - (PlacesClient, transports.PlacesGrpcTransport, "grpc", "true"), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (PlacesClient, transports.PlacesGrpcTransport, "grpc", "false"), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (PlacesClient, transports.PlacesRestTransport, "rest", "true"), - (PlacesClient, transports.PlacesRestTransport, "rest", "false"), -]) -@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) -@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_places_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", [ - PlacesClient, PlacesAsyncClient -]) -@mock.patch.object(PlacesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PlacesClient)) -@mock.patch.object(PlacesAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(PlacesAsyncClient)) -def test_places_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", [ - PlacesClient, PlacesAsyncClient -]) -@mock.patch.object(PlacesClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesClient)) -@mock.patch.object(PlacesAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(PlacesAsyncClient)) -def test_places_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = PlacesClient._DEFAULT_UNIVERSE - default_endpoint = PlacesClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = PlacesClient._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", [ - (PlacesClient, transports.PlacesGrpcTransport, "grpc"), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio"), - (PlacesClient, transports.PlacesRestTransport, "rest"), -]) -def test_places_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", [ - (PlacesClient, transports.PlacesGrpcTransport, "grpc", grpc_helpers), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (PlacesClient, transports.PlacesRestTransport, "rest", None), -]) -def test_places_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_places_client_client_options_from_dict(): - with mock.patch('google.maps.places_v1.services.places.transports.PlacesGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = PlacesClient( - 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", [ - (PlacesClient, transports.PlacesGrpcTransport, "grpc", grpc_helpers), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_places_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( - "places.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="places.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - places_service.SearchNearbyRequest, - dict, -]) -def test_search_nearby(request_type, transport: str = 'grpc'): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_nearby), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.SearchNearbyResponse( - ) - response = client.search_nearby(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = places_service.SearchNearbyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchNearbyResponse) - - -def test_search_nearby_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 = PlacesClient( - 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 = places_service.SearchNearbyRequest( - language_code='language_code_value', - region_code='region_code_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_nearby), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.search_nearby(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == places_service.SearchNearbyRequest( - language_code='language_code_value', - region_code='region_code_value', - ) - -def test_search_nearby_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 = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.search_nearby in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.search_nearby] = mock_rpc - request = {} - client.search_nearby(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_nearby(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_search_nearby_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 = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.search_nearby in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.search_nearby] = mock_rpc - - request = {} - await client.search_nearby(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.search_nearby(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_search_nearby_async(transport: str = 'grpc_asyncio', request_type=places_service.SearchNearbyRequest): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_nearby), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchNearbyResponse( - )) - response = await client.search_nearby(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = places_service.SearchNearbyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchNearbyResponse) - - -@pytest.mark.asyncio -async def test_search_nearby_async_from_dict(): - await test_search_nearby_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - places_service.SearchTextRequest, - dict, -]) -def test_search_text(request_type, transport: str = 'grpc'): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_text), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.SearchTextResponse( - ) - response = client.search_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = places_service.SearchTextRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchTextResponse) - - -def test_search_text_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 = PlacesClient( - 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 = places_service.SearchTextRequest( - text_query='text_query_value', - language_code='language_code_value', - region_code='region_code_value', - included_type='included_type_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_text), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.search_text(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == places_service.SearchTextRequest( - text_query='text_query_value', - language_code='language_code_value', - region_code='region_code_value', - included_type='included_type_value', - ) - -def test_search_text_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 = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.search_text in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.search_text] = mock_rpc - request = {} - client.search_text(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_text(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_search_text_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 = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.search_text in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.search_text] = mock_rpc - - request = {} - await client.search_text(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.search_text(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_search_text_async(transport: str = 'grpc_asyncio', request_type=places_service.SearchTextRequest): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_text), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchTextResponse( - )) - response = await client.search_text(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = places_service.SearchTextRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchTextResponse) - - -@pytest.mark.asyncio -async def test_search_text_async_from_dict(): - await test_search_text_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - places_service.GetPhotoMediaRequest, - dict, -]) -def test_get_photo_media(request_type, transport: str = 'grpc'): - client = PlacesClient( - 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_photo_media), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.PhotoMedia( - name='name_value', - photo_uri='photo_uri_value', - ) - response = client.get_photo_media(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = places_service.GetPhotoMediaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.PhotoMedia) - assert response.name == 'name_value' - assert response.photo_uri == 'photo_uri_value' - - -def test_get_photo_media_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 = PlacesClient( - 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 = places_service.GetPhotoMediaRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_photo_media(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == places_service.GetPhotoMediaRequest( - name='name_value', - ) - -def test_get_photo_media_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 = PlacesClient( - 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_photo_media 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_photo_media] = mock_rpc - request = {} - client.get_photo_media(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_photo_media(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_photo_media_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 = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_photo_media 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_photo_media] = mock_rpc - - request = {} - await client.get_photo_media(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_photo_media(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_photo_media_async(transport: str = 'grpc_asyncio', request_type=places_service.GetPhotoMediaRequest): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia( - name='name_value', - photo_uri='photo_uri_value', - )) - response = await client.get_photo_media(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = places_service.GetPhotoMediaRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.PhotoMedia) - assert response.name == 'name_value' - assert response.photo_uri == 'photo_uri_value' - - -@pytest.mark.asyncio -async def test_get_photo_media_async_from_dict(): - await test_get_photo_media_async(request_type=dict) - -def test_get_photo_media_field_headers(): - client = PlacesClient( - 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 = places_service.GetPhotoMediaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - call.return_value = places_service.PhotoMedia() - client.get_photo_media(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_photo_media_field_headers_async(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = places_service.GetPhotoMediaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia()) - await client.get_photo_media(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_photo_media_flattened(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.PhotoMedia() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_photo_media( - 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_photo_media_flattened_error(): - client = PlacesClient( - 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_photo_media( - places_service.GetPhotoMediaRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_photo_media_flattened_async(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.PhotoMedia() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_photo_media( - 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_photo_media_flattened_error_async(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_photo_media( - places_service.GetPhotoMediaRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - places_service.GetPlaceRequest, - dict, -]) -def test_get_place(request_type, transport: str = 'grpc'): - client = PlacesClient( - 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_place), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = place.Place( - name='name_value', - id='id_value', - types=['types_value'], - primary_type='primary_type_value', - national_phone_number='national_phone_number_value', - international_phone_number='international_phone_number_value', - formatted_address='formatted_address_value', - short_formatted_address='short_formatted_address_value', - rating=0.645, - google_maps_uri='google_maps_uri_value', - website_uri='website_uri_value', - utc_offset_minutes=1942, - adr_format_address='adr_format_address_value', - business_status=place.Place.BusinessStatus.OPERATIONAL, - price_level=place.PriceLevel.PRICE_LEVEL_FREE, - user_rating_count=1835, - icon_mask_base_uri='icon_mask_base_uri_value', - icon_background_color='icon_background_color_value', - takeout=True, - delivery=True, - dine_in=True, - curbside_pickup=True, - reservable=True, - serves_breakfast=True, - serves_lunch=True, - serves_dinner=True, - serves_beer=True, - serves_wine=True, - serves_brunch=True, - serves_vegetarian_food=True, - outdoor_seating=True, - live_music=True, - menu_for_children=True, - serves_cocktails=True, - serves_dessert=True, - serves_coffee=True, - good_for_children=True, - allows_dogs=True, - restroom=True, - good_for_groups=True, - good_for_watching_sports=True, - pure_service_area_business=True, - ) - response = client.get_place(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = places_service.GetPlaceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, place.Place) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.types == ['types_value'] - assert response.primary_type == 'primary_type_value' - assert response.national_phone_number == 'national_phone_number_value' - assert response.international_phone_number == 'international_phone_number_value' - assert response.formatted_address == 'formatted_address_value' - assert response.short_formatted_address == 'short_formatted_address_value' - assert math.isclose(response.rating, 0.645, rel_tol=1e-6) - assert response.google_maps_uri == 'google_maps_uri_value' - assert response.website_uri == 'website_uri_value' - assert response.utc_offset_minutes == 1942 - assert response.adr_format_address == 'adr_format_address_value' - assert response.business_status == place.Place.BusinessStatus.OPERATIONAL - assert response.price_level == place.PriceLevel.PRICE_LEVEL_FREE - assert response.user_rating_count == 1835 - assert response.icon_mask_base_uri == 'icon_mask_base_uri_value' - assert response.icon_background_color == 'icon_background_color_value' - assert response.takeout is True - assert response.delivery is True - assert response.dine_in is True - assert response.curbside_pickup is True - assert response.reservable is True - assert response.serves_breakfast is True - assert response.serves_lunch is True - assert response.serves_dinner is True - assert response.serves_beer is True - assert response.serves_wine is True - assert response.serves_brunch is True - assert response.serves_vegetarian_food is True - assert response.outdoor_seating is True - assert response.live_music is True - assert response.menu_for_children is True - assert response.serves_cocktails is True - assert response.serves_dessert is True - assert response.serves_coffee is True - assert response.good_for_children is True - assert response.allows_dogs is True - assert response.restroom is True - assert response.good_for_groups is True - assert response.good_for_watching_sports is True - assert response.pure_service_area_business is True - - -def test_get_place_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 = PlacesClient( - 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 = places_service.GetPlaceRequest( - name='name_value', - language_code='language_code_value', - region_code='region_code_value', - session_token='session_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_place(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == places_service.GetPlaceRequest( - name='name_value', - language_code='language_code_value', - region_code='region_code_value', - session_token='session_token_value', - ) - -def test_get_place_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 = PlacesClient( - 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_place 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_place] = mock_rpc - request = {} - client.get_place(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_place(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_place_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 = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_place 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_place] = mock_rpc - - request = {} - await client.get_place(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_place(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_place_async(transport: str = 'grpc_asyncio', request_type=places_service.GetPlaceRequest): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(place.Place( - name='name_value', - id='id_value', - types=['types_value'], - primary_type='primary_type_value', - national_phone_number='national_phone_number_value', - international_phone_number='international_phone_number_value', - formatted_address='formatted_address_value', - short_formatted_address='short_formatted_address_value', - rating=0.645, - google_maps_uri='google_maps_uri_value', - website_uri='website_uri_value', - utc_offset_minutes=1942, - adr_format_address='adr_format_address_value', - business_status=place.Place.BusinessStatus.OPERATIONAL, - price_level=place.PriceLevel.PRICE_LEVEL_FREE, - user_rating_count=1835, - icon_mask_base_uri='icon_mask_base_uri_value', - icon_background_color='icon_background_color_value', - takeout=True, - delivery=True, - dine_in=True, - curbside_pickup=True, - reservable=True, - serves_breakfast=True, - serves_lunch=True, - serves_dinner=True, - serves_beer=True, - serves_wine=True, - serves_brunch=True, - serves_vegetarian_food=True, - outdoor_seating=True, - live_music=True, - menu_for_children=True, - serves_cocktails=True, - serves_dessert=True, - serves_coffee=True, - good_for_children=True, - allows_dogs=True, - restroom=True, - good_for_groups=True, - good_for_watching_sports=True, - pure_service_area_business=True, - )) - response = await client.get_place(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = places_service.GetPlaceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, place.Place) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.types == ['types_value'] - assert response.primary_type == 'primary_type_value' - assert response.national_phone_number == 'national_phone_number_value' - assert response.international_phone_number == 'international_phone_number_value' - assert response.formatted_address == 'formatted_address_value' - assert response.short_formatted_address == 'short_formatted_address_value' - assert math.isclose(response.rating, 0.645, rel_tol=1e-6) - assert response.google_maps_uri == 'google_maps_uri_value' - assert response.website_uri == 'website_uri_value' - assert response.utc_offset_minutes == 1942 - assert response.adr_format_address == 'adr_format_address_value' - assert response.business_status == place.Place.BusinessStatus.OPERATIONAL - assert response.price_level == place.PriceLevel.PRICE_LEVEL_FREE - assert response.user_rating_count == 1835 - assert response.icon_mask_base_uri == 'icon_mask_base_uri_value' - assert response.icon_background_color == 'icon_background_color_value' - assert response.takeout is True - assert response.delivery is True - assert response.dine_in is True - assert response.curbside_pickup is True - assert response.reservable is True - assert response.serves_breakfast is True - assert response.serves_lunch is True - assert response.serves_dinner is True - assert response.serves_beer is True - assert response.serves_wine is True - assert response.serves_brunch is True - assert response.serves_vegetarian_food is True - assert response.outdoor_seating is True - assert response.live_music is True - assert response.menu_for_children is True - assert response.serves_cocktails is True - assert response.serves_dessert is True - assert response.serves_coffee is True - assert response.good_for_children is True - assert response.allows_dogs is True - assert response.restroom is True - assert response.good_for_groups is True - assert response.good_for_watching_sports is True - assert response.pure_service_area_business is True - - -@pytest.mark.asyncio -async def test_get_place_async_from_dict(): - await test_get_place_async(request_type=dict) - -def test_get_place_field_headers(): - client = PlacesClient( - 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 = places_service.GetPlaceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - call.return_value = place.Place() - client.get_place(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_place_field_headers_async(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = places_service.GetPlaceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(place.Place()) - await client.get_place(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_place_flattened(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = place.Place() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_place( - 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_place_flattened_error(): - client = PlacesClient( - 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_place( - places_service.GetPlaceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_place_flattened_async(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = place.Place() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(place.Place()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_place( - 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_place_flattened_error_async(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_place( - places_service.GetPlaceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - places_service.AutocompletePlacesRequest, - dict, -]) -def test_autocomplete_places(request_type, transport: str = 'grpc'): - client = PlacesClient( - 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.autocomplete_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = places_service.AutocompletePlacesResponse( - ) - response = client.autocomplete_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = places_service.AutocompletePlacesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.AutocompletePlacesResponse) - - -def test_autocomplete_places_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 = PlacesClient( - 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 = places_service.AutocompletePlacesRequest( - input='input_value', - language_code='language_code_value', - region_code='region_code_value', - session_token='session_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.autocomplete_places), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.autocomplete_places(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == places_service.AutocompletePlacesRequest( - input='input_value', - language_code='language_code_value', - region_code='region_code_value', - session_token='session_token_value', - ) - -def test_autocomplete_places_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 = PlacesClient( - 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.autocomplete_places 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.autocomplete_places] = mock_rpc - request = {} - client.autocomplete_places(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.autocomplete_places(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_autocomplete_places_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 = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.autocomplete_places 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.autocomplete_places] = mock_rpc - - request = {} - await client.autocomplete_places(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.autocomplete_places(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_autocomplete_places_async(transport: str = 'grpc_asyncio', request_type=places_service.AutocompletePlacesRequest): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.autocomplete_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(places_service.AutocompletePlacesResponse( - )) - response = await client.autocomplete_places(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = places_service.AutocompletePlacesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.AutocompletePlacesResponse) - - -@pytest.mark.asyncio -async def test_autocomplete_places_async_from_dict(): - await test_autocomplete_places_async(request_type=dict) - - -def test_search_nearby_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 = PlacesClient( - 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.search_nearby in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.search_nearby] = mock_rpc - - request = {} - client.search_nearby(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_nearby(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_search_nearby_rest_required_fields(request_type=places_service.SearchNearbyRequest): - transport_class = transports.PlacesRestTransport - - 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()).search_nearby._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()).search_nearby._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = places_service.SearchNearbyResponse() - # 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 = places_service.SearchNearbyResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.search_nearby(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_nearby_rest_unset_required_fields(): - transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search_nearby._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("locationRestriction", ))) - - -def test_search_text_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 = PlacesClient( - 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.search_text in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.search_text] = mock_rpc - - request = {} - client.search_text(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.search_text(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_search_text_rest_required_fields(request_type=places_service.SearchTextRequest): - transport_class = transports.PlacesRestTransport - - request_init = {} - request_init["text_query"] = "" - 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()).search_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["textQuery"] = 'text_query_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_text._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "textQuery" in jsonified_request - assert jsonified_request["textQuery"] == 'text_query_value' - - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = places_service.SearchTextResponse() - # 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 = places_service.SearchTextResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.search_text(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_text_rest_unset_required_fields(): - transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search_text._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("textQuery", ))) - - -def test_get_photo_media_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 = PlacesClient( - 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_photo_media 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_photo_media] = mock_rpc - - request = {} - client.get_photo_media(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_photo_media(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_photo_media_rest_required_fields(request_type=places_service.GetPhotoMediaRequest): - transport_class = transports.PlacesRestTransport - - 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_photo_media._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_photo_media._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("max_height_px", "max_width_px", "skip_http_redirect", )) - 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 = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = places_service.PhotoMedia() - # 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 = places_service.PhotoMedia.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_photo_media(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_photo_media_rest_unset_required_fields(): - transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_photo_media._get_unset_required_fields({}) - assert set(unset_fields) == (set(("maxHeightPx", "maxWidthPx", "skipHttpRedirect", )) & set(("name", ))) - - -def test_get_photo_media_rest_flattened(): - client = PlacesClient( - 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 = places_service.PhotoMedia() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'places/sample1/photos/sample2/media'} - - # 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 = places_service.PhotoMedia.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_photo_media(**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=places/*/photos/*/media}" % client.transport._host, args[1]) - - -def test_get_photo_media_rest_flattened_error(transport: str = 'rest'): - client = PlacesClient( - 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_photo_media( - places_service.GetPhotoMediaRequest(), - name='name_value', - ) - - -def test_get_place_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 = PlacesClient( - 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_place 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_place] = mock_rpc - - request = {} - client.get_place(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_place(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_place_rest_required_fields(request_type=places_service.GetPlaceRequest): - transport_class = transports.PlacesRestTransport - - 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_place._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_place._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", "region_code", "session_token", )) - 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 = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = place.Place() - # 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 = place.Place.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_place(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_place_rest_unset_required_fields(): - transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_place._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", "regionCode", "sessionToken", )) & set(("name", ))) - - -def test_get_place_rest_flattened(): - client = PlacesClient( - 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 = place.Place() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'places/sample1'} - - # 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 = place.Place.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_place(**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=places/*}" % client.transport._host, args[1]) - - -def test_get_place_rest_flattened_error(transport: str = 'rest'): - client = PlacesClient( - 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_place( - places_service.GetPlaceRequest(), - name='name_value', - ) - - -def test_autocomplete_places_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 = PlacesClient( - 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.autocomplete_places 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.autocomplete_places] = mock_rpc - - request = {} - client.autocomplete_places(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.autocomplete_places(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_autocomplete_places_rest_required_fields(request_type=places_service.AutocompletePlacesRequest): - transport_class = transports.PlacesRestTransport - - request_init = {} - request_init["input"] = "" - 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()).autocomplete_places._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["input"] = 'input_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).autocomplete_places._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "input" in jsonified_request - assert jsonified_request["input"] == 'input_value' - - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = places_service.AutocompletePlacesResponse() - # 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 = places_service.AutocompletePlacesResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.autocomplete_places(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_autocomplete_places_rest_unset_required_fields(): - transport = transports.PlacesRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.autocomplete_places._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("input", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PlacesClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = PlacesClient( - 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 = PlacesClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = PlacesClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = PlacesClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.PlacesGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.PlacesGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.PlacesGrpcTransport, - transports.PlacesGrpcAsyncIOTransport, - transports.PlacesRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = PlacesClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_search_nearby_empty_call_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_nearby), - '__call__') as call: - call.return_value = places_service.SearchNearbyResponse() - client.search_nearby(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchNearbyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_search_text_empty_call_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_text), - '__call__') as call: - call.return_value = places_service.SearchTextResponse() - client.search_text(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchTextRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_photo_media_empty_call_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - call.return_value = places_service.PhotoMedia() - client.get_photo_media(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPhotoMediaRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_place_empty_call_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - call.return_value = place.Place() - client.get_place(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPlaceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_autocomplete_places_empty_call_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.autocomplete_places), - '__call__') as call: - call.return_value = places_service.AutocompletePlacesResponse() - client.autocomplete_places(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.AutocompletePlacesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = PlacesAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_search_nearby_empty_call_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_nearby), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchNearbyResponse( - )) - await client.search_nearby(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchNearbyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_search_text_empty_call_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_text), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.SearchTextResponse( - )) - await client.search_text(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchTextRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_photo_media_empty_call_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.PhotoMedia( - name='name_value', - photo_uri='photo_uri_value', - )) - await client.get_photo_media(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPhotoMediaRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_place_empty_call_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(place.Place( - name='name_value', - id='id_value', - types=['types_value'], - primary_type='primary_type_value', - national_phone_number='national_phone_number_value', - international_phone_number='international_phone_number_value', - formatted_address='formatted_address_value', - short_formatted_address='short_formatted_address_value', - rating=0.645, - google_maps_uri='google_maps_uri_value', - website_uri='website_uri_value', - utc_offset_minutes=1942, - adr_format_address='adr_format_address_value', - business_status=place.Place.BusinessStatus.OPERATIONAL, - price_level=place.PriceLevel.PRICE_LEVEL_FREE, - user_rating_count=1835, - icon_mask_base_uri='icon_mask_base_uri_value', - icon_background_color='icon_background_color_value', - takeout=True, - delivery=True, - dine_in=True, - curbside_pickup=True, - reservable=True, - serves_breakfast=True, - serves_lunch=True, - serves_dinner=True, - serves_beer=True, - serves_wine=True, - serves_brunch=True, - serves_vegetarian_food=True, - outdoor_seating=True, - live_music=True, - menu_for_children=True, - serves_cocktails=True, - serves_dessert=True, - serves_coffee=True, - good_for_children=True, - allows_dogs=True, - restroom=True, - good_for_groups=True, - good_for_watching_sports=True, - pure_service_area_business=True, - )) - await client.get_place(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPlaceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_autocomplete_places_empty_call_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.autocomplete_places), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(places_service.AutocompletePlacesResponse( - )) - await client.autocomplete_places(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.AutocompletePlacesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = PlacesClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_search_nearby_rest_bad_request(request_type=places_service.SearchNearbyRequest): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.search_nearby(request) - - -@pytest.mark.parametrize("request_type", [ - places_service.SearchNearbyRequest, - dict, -]) -def test_search_nearby_rest_call_success(request_type): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = places_service.SearchNearbyResponse( - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = places_service.SearchNearbyResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.search_nearby(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchNearbyResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_nearby_rest_interceptors(null_interceptor): - transport = transports.PlacesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), - ) - client = PlacesClient(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.PlacesRestInterceptor, "post_search_nearby") as post, \ - mock.patch.object(transports.PlacesRestInterceptor, "pre_search_nearby") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = places_service.SearchNearbyRequest.pb(places_service.SearchNearbyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = places_service.SearchNearbyResponse.to_json(places_service.SearchNearbyResponse()) - req.return_value.content = return_value - - request = places_service.SearchNearbyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = places_service.SearchNearbyResponse() - - client.search_nearby(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_text_rest_bad_request(request_type=places_service.SearchTextRequest): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.search_text(request) - - -@pytest.mark.parametrize("request_type", [ - places_service.SearchTextRequest, - dict, -]) -def test_search_text_rest_call_success(request_type): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = places_service.SearchTextResponse( - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = places_service.SearchTextResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.search_text(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.SearchTextResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_text_rest_interceptors(null_interceptor): - transport = transports.PlacesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), - ) - client = PlacesClient(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.PlacesRestInterceptor, "post_search_text") as post, \ - mock.patch.object(transports.PlacesRestInterceptor, "pre_search_text") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = places_service.SearchTextRequest.pb(places_service.SearchTextRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = places_service.SearchTextResponse.to_json(places_service.SearchTextResponse()) - req.return_value.content = return_value - - request = places_service.SearchTextRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = places_service.SearchTextResponse() - - client.search_text(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_photo_media_rest_bad_request(request_type=places_service.GetPhotoMediaRequest): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'places/sample1/photos/sample2/media'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_photo_media(request) - - -@pytest.mark.parametrize("request_type", [ - places_service.GetPhotoMediaRequest, - dict, -]) -def test_get_photo_media_rest_call_success(request_type): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'places/sample1/photos/sample2/media'} - 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 = places_service.PhotoMedia( - name='name_value', - photo_uri='photo_uri_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = places_service.PhotoMedia.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_photo_media(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.PhotoMedia) - assert response.name == 'name_value' - assert response.photo_uri == 'photo_uri_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_photo_media_rest_interceptors(null_interceptor): - transport = transports.PlacesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), - ) - client = PlacesClient(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.PlacesRestInterceptor, "post_get_photo_media") as post, \ - mock.patch.object(transports.PlacesRestInterceptor, "pre_get_photo_media") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = places_service.GetPhotoMediaRequest.pb(places_service.GetPhotoMediaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = places_service.PhotoMedia.to_json(places_service.PhotoMedia()) - req.return_value.content = return_value - - request = places_service.GetPhotoMediaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = places_service.PhotoMedia() - - client.get_photo_media(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_place_rest_bad_request(request_type=places_service.GetPlaceRequest): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'places/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 = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_place(request) - - -@pytest.mark.parametrize("request_type", [ - places_service.GetPlaceRequest, - dict, -]) -def test_get_place_rest_call_success(request_type): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'places/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 = place.Place( - name='name_value', - id='id_value', - types=['types_value'], - primary_type='primary_type_value', - national_phone_number='national_phone_number_value', - international_phone_number='international_phone_number_value', - formatted_address='formatted_address_value', - short_formatted_address='short_formatted_address_value', - rating=0.645, - google_maps_uri='google_maps_uri_value', - website_uri='website_uri_value', - utc_offset_minutes=1942, - adr_format_address='adr_format_address_value', - business_status=place.Place.BusinessStatus.OPERATIONAL, - price_level=place.PriceLevel.PRICE_LEVEL_FREE, - user_rating_count=1835, - icon_mask_base_uri='icon_mask_base_uri_value', - icon_background_color='icon_background_color_value', - takeout=True, - delivery=True, - dine_in=True, - curbside_pickup=True, - reservable=True, - serves_breakfast=True, - serves_lunch=True, - serves_dinner=True, - serves_beer=True, - serves_wine=True, - serves_brunch=True, - serves_vegetarian_food=True, - outdoor_seating=True, - live_music=True, - menu_for_children=True, - serves_cocktails=True, - serves_dessert=True, - serves_coffee=True, - good_for_children=True, - allows_dogs=True, - restroom=True, - good_for_groups=True, - good_for_watching_sports=True, - pure_service_area_business=True, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = place.Place.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_place(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, place.Place) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.types == ['types_value'] - assert response.primary_type == 'primary_type_value' - assert response.national_phone_number == 'national_phone_number_value' - assert response.international_phone_number == 'international_phone_number_value' - assert response.formatted_address == 'formatted_address_value' - assert response.short_formatted_address == 'short_formatted_address_value' - assert math.isclose(response.rating, 0.645, rel_tol=1e-6) - assert response.google_maps_uri == 'google_maps_uri_value' - assert response.website_uri == 'website_uri_value' - assert response.utc_offset_minutes == 1942 - assert response.adr_format_address == 'adr_format_address_value' - assert response.business_status == place.Place.BusinessStatus.OPERATIONAL - assert response.price_level == place.PriceLevel.PRICE_LEVEL_FREE - assert response.user_rating_count == 1835 - assert response.icon_mask_base_uri == 'icon_mask_base_uri_value' - assert response.icon_background_color == 'icon_background_color_value' - assert response.takeout is True - assert response.delivery is True - assert response.dine_in is True - assert response.curbside_pickup is True - assert response.reservable is True - assert response.serves_breakfast is True - assert response.serves_lunch is True - assert response.serves_dinner is True - assert response.serves_beer is True - assert response.serves_wine is True - assert response.serves_brunch is True - assert response.serves_vegetarian_food is True - assert response.outdoor_seating is True - assert response.live_music is True - assert response.menu_for_children is True - assert response.serves_cocktails is True - assert response.serves_dessert is True - assert response.serves_coffee is True - assert response.good_for_children is True - assert response.allows_dogs is True - assert response.restroom is True - assert response.good_for_groups is True - assert response.good_for_watching_sports is True - assert response.pure_service_area_business is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_place_rest_interceptors(null_interceptor): - transport = transports.PlacesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), - ) - client = PlacesClient(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.PlacesRestInterceptor, "post_get_place") as post, \ - mock.patch.object(transports.PlacesRestInterceptor, "pre_get_place") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = places_service.GetPlaceRequest.pb(places_service.GetPlaceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = place.Place.to_json(place.Place()) - req.return_value.content = return_value - - request = places_service.GetPlaceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = place.Place() - - client.get_place(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_autocomplete_places_rest_bad_request(request_type=places_service.AutocompletePlacesRequest): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.autocomplete_places(request) - - -@pytest.mark.parametrize("request_type", [ - places_service.AutocompletePlacesRequest, - dict, -]) -def test_autocomplete_places_rest_call_success(request_type): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = places_service.AutocompletePlacesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = places_service.AutocompletePlacesResponse.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 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.autocomplete_places(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, places_service.AutocompletePlacesResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_autocomplete_places_rest_interceptors(null_interceptor): - transport = transports.PlacesRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.PlacesRestInterceptor(), - ) - client = PlacesClient(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.PlacesRestInterceptor, "post_autocomplete_places") as post, \ - mock.patch.object(transports.PlacesRestInterceptor, "pre_autocomplete_places") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = places_service.AutocompletePlacesRequest.pb(places_service.AutocompletePlacesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = places_service.AutocompletePlacesResponse.to_json(places_service.AutocompletePlacesResponse()) - req.return_value.content = return_value - - request = places_service.AutocompletePlacesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = places_service.AutocompletePlacesResponse() - - client.autocomplete_places(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - -def test_initialize_client_w_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_search_nearby_empty_call_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_nearby), - '__call__') as call: - client.search_nearby(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchNearbyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_search_text_empty_call_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.search_text), - '__call__') as call: - client.search_text(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.SearchTextRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_photo_media_empty_call_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_photo_media), - '__call__') as call: - client.get_photo_media(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPhotoMediaRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_place_empty_call_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_place), - '__call__') as call: - client.get_place(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.GetPlaceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_autocomplete_places_empty_call_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.autocomplete_places), - '__call__') as call: - client.autocomplete_places(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = places_service.AutocompletePlacesRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.PlacesGrpcTransport, - ) - -def test_places_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.PlacesTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_places_base_transport(): - # Instantiate the base transport. - with mock.patch('google.maps.places_v1.services.places.transports.PlacesTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.PlacesTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search_nearby', - 'search_text', - 'get_photo_media', - 'get_place', - 'autocomplete_places', - ) - 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_places_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.places_v1.services.places.transports.PlacesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PlacesTransport( - 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_places_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.places_v1.services.places.transports.PlacesTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.PlacesTransport() - adc.assert_called_once() - - -def test_places_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) - PlacesClient() - 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.PlacesGrpcTransport, - transports.PlacesGrpcAsyncIOTransport, - ], -) -def test_places_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.PlacesGrpcTransport, - transports.PlacesGrpcAsyncIOTransport, - transports.PlacesRestTransport, - ], -) -def test_places_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.PlacesGrpcTransport, grpc_helpers), - (transports.PlacesGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_places_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( - "places.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="places.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.PlacesGrpcTransport, transports.PlacesGrpcAsyncIOTransport]) -def test_places_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_places_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.PlacesRestTransport ( - 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_places_host_no_port(transport_name): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='places.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'places.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://places.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_places_host_with_port(transport_name): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='places.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'places.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://places.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_places_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = PlacesClient( - credentials=creds1, - transport=transport_name, - ) - client2 = PlacesClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.search_nearby._session - session2 = client2.transport.search_nearby._session - assert session1 != session2 - session1 = client1.transport.search_text._session - session2 = client2.transport.search_text._session - assert session1 != session2 - session1 = client1.transport.get_photo_media._session - session2 = client2.transport.get_photo_media._session - assert session1 != session2 - session1 = client1.transport.get_place._session - session2 = client2.transport.get_place._session - assert session1 != session2 - session1 = client1.transport.autocomplete_places._session - session2 = client2.transport.autocomplete_places._session - assert session1 != session2 -def test_places_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PlacesGrpcTransport( - 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_places_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.PlacesGrpcAsyncIOTransport( - 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.PlacesGrpcTransport, transports.PlacesGrpcAsyncIOTransport]) -def test_places_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.PlacesGrpcTransport, transports.PlacesGrpcAsyncIOTransport]) -def test_places_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_photo_path(): - place = "squid" - photo = "clam" - expected = "places/{place}/photos/{photo}".format(place=place, photo=photo, ) - actual = PlacesClient.photo_path(place, photo) - assert expected == actual - - -def test_parse_photo_path(): - expected = { - "place": "whelk", - "photo": "octopus", - } - path = PlacesClient.photo_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_photo_path(path) - assert expected == actual - -def test_photo_media_path(): - place_id = "oyster" - photo_reference = "nudibranch" - expected = "places/{place_id}/photos/{photo_reference}/media".format(place_id=place_id, photo_reference=photo_reference, ) - actual = PlacesClient.photo_media_path(place_id, photo_reference) - assert expected == actual - - -def test_parse_photo_media_path(): - expected = { - "place_id": "cuttlefish", - "photo_reference": "mussel", - } - path = PlacesClient.photo_media_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_photo_media_path(path) - assert expected == actual - -def test_place_path(): - place_id = "winkle" - expected = "places/{place_id}".format(place_id=place_id, ) - actual = PlacesClient.place_path(place_id) - assert expected == actual - - -def test_parse_place_path(): - expected = { - "place_id": "nautilus", - } - path = PlacesClient.place_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_place_path(path) - assert expected == actual - -def test_review_path(): - place = "scallop" - review = "abalone" - expected = "places/{place}/reviews/{review}".format(place=place, review=review, ) - actual = PlacesClient.review_path(place, review) - assert expected == actual - - -def test_parse_review_path(): - expected = { - "place": "squid", - "review": "clam", - } - path = PlacesClient.review_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_review_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = PlacesClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = PlacesClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = PlacesClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = PlacesClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = PlacesClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = PlacesClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = PlacesClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = PlacesClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = PlacesClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = PlacesClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = PlacesClient.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.PlacesTransport, '_prep_wrapped_messages') as prep: - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.PlacesTransport, '_prep_wrapped_messages') as prep: - transport_class = PlacesClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_transport_close_grpc(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = PlacesAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = PlacesClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = PlacesClient( - 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", [ - (PlacesClient, transports.PlacesGrpcTransport), - (PlacesAsyncClient, transports.PlacesGrpcAsyncIOTransport), -]) -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-places/google/maps/places/gapic_version.py b/packages/google-maps-places/google/maps/places/gapic_version.py index fe189ff85cf7..558c8aab67c5 100644 --- a/packages/google-maps-places/google/maps/places/gapic_version.py +++ b/packages/google-maps-places/google/maps/places/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.22" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-places/google/maps/places_v1/gapic_version.py b/packages/google-maps-places/google/maps/places_v1/gapic_version.py index fe189ff85cf7..558c8aab67c5 100644 --- a/packages/google-maps-places/google/maps/places_v1/gapic_version.py +++ b/packages/google-maps-places/google/maps/places_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.22" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-places/google/maps/places_v1/services/places/transports/base.py b/packages/google-maps-places/google/maps/places_v1/services/places/transports/base.py index 07da32ce4800..d3d350aca477 100644 --- a/packages/google-maps-places/google/maps/places_v1/services/places/transports/base.py +++ b/packages/google-maps-places/google/maps/places_v1/services/places/transports/base.py @@ -35,7 +35,7 @@ class PlacesTransport(abc.ABC): """Abstract transport class for Places.""" - AUTH_SCOPES = () + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) DEFAULT_HOST: str = "places.googleapis.com" diff --git a/packages/google-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json b/packages/google-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json index 9c735ca0be50..bea29a42b294 100644 --- a/packages/google-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json +++ b/packages/google-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-places", - "version": "0.1.22" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py b/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py index d2290b7fdf33..bccb449feb76 100644 --- a/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py +++ b/packages/google-maps-places/tests/unit/gapic/places_v1/test_places.py @@ -998,7 +998,7 @@ def test_places_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=(), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=None, default_host="places.googleapis.com", ssl_credentials=None, @@ -4378,7 +4378,7 @@ def test_places_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=(), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) @@ -4401,7 +4401,7 @@ def test_places_auth_adc(): PlacesClient() adc.assert_called_once_with( scopes=None, - default_scopes=(), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id=None, ) @@ -4421,7 +4421,7 @@ def test_places_transport_auth_adc(transport_class): transport_class(quota_project_id="octopus", scopes=["1", "2"]) adc.assert_called_once_with( scopes=["1", "2"], - default_scopes=(), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) @@ -4473,7 +4473,7 @@ def test_places_transport_create_channel(transport_class, grpc_helpers): credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=(), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=["1", "2"], default_host="places.googleapis.com", ssl_credentials=None,