From 430cb7b632f81043f61f80758c0395824b2e3e3a Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 22 Mar 2023 20:16:18 +0000 Subject: [PATCH 1/2] docs: Fix formatting of request arg in docstring chore: Update gapic-generator-python to v1.9.1 PiperOrigin-RevId: 518604533 Source-Link: https://github.com/googleapis/googleapis/commit/8a085aeddfa010af5bcef090827aac5255383d7e Source-Link: https://github.com/googleapis/googleapis-gen/commit/b2ab4b0a0ae2907e812c209198a74e0898afcb04 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjJhYjRiMGEwYWUyOTA3ZTgxMmMyMDkxOThhNzRlMDg5OGFmY2IwNCJ9 --- owl-bot-staging/v1/.coveragerc | 13 + owl-bot-staging/v1/.flake8 | 33 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 + owl-bot-staging/v1/docs/index.rst | 7 + .../v1/docs/iot_v1/device_manager.rst | 10 + owl-bot-staging/v1/docs/iot_v1/services.rst | 6 + owl-bot-staging/v1/docs/iot_v1/types.rst | 6 + .../v1/google/cloud/iot/__init__.py | 117 + .../v1/google/cloud/iot/gapic_version.py | 16 + owl-bot-staging/v1/google/cloud/iot/py.typed | 2 + .../v1/google/cloud/iot_v1/__init__.py | 118 + .../google/cloud/iot_v1/gapic_metadata.json | 313 + .../v1/google/cloud/iot_v1/gapic_version.py | 16 + .../v1/google/cloud/iot_v1/py.typed | 2 + .../google/cloud/iot_v1/services/__init__.py | 15 + .../services/device_manager/__init__.py | 22 + .../services/device_manager/async_client.py | 2477 ++++ .../iot_v1/services/device_manager/client.py | 2617 ++++ .../iot_v1/services/device_manager/pagers.py | 261 + .../device_manager/transports/__init__.py | 38 + .../device_manager/transports/base.py | 477 + .../device_manager/transports/grpc.py | 763 ++ .../device_manager/transports/grpc_asyncio.py | 762 ++ .../device_manager/transports/rest.py | 2535 ++++ .../v1/google/cloud/iot_v1/types/__init__.py | 112 + .../cloud/iot_v1/types/device_manager.py | 688 + .../v1/google/cloud/iot_v1/types/resources.py | 868 ++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 184 + ...ce_manager_bind_device_to_gateway_async.py | 54 + ...ice_manager_bind_device_to_gateway_sync.py | 54 + ...ated_device_manager_create_device_async.py | 52 + ...ce_manager_create_device_registry_async.py | 52 + ...ice_manager_create_device_registry_sync.py | 52 + ...rated_device_manager_create_device_sync.py | 52 + ...ated_device_manager_delete_device_async.py | 50 + ...ce_manager_delete_device_registry_async.py | 50 + ...ice_manager_delete_device_registry_sync.py | 50 + ...rated_device_manager_delete_device_sync.py | 50 + ...nerated_device_manager_get_device_async.py | 52 + ...evice_manager_get_device_registry_async.py | 52 + ...device_manager_get_device_registry_sync.py | 52 + ...enerated_device_manager_get_device_sync.py | 52 + ...ted_device_manager_get_iam_policy_async.py | 53 + ...ated_device_manager_get_iam_policy_sync.py | 53 + ...nager_list_device_config_versions_async.py | 52 + ...anager_list_device_config_versions_sync.py | 52 + ...ce_manager_list_device_registries_async.py | 53 + ...ice_manager_list_device_registries_sync.py | 53 + ...device_manager_list_device_states_async.py | 52 + ..._device_manager_list_device_states_sync.py | 52 + ...rated_device_manager_list_devices_async.py | 53 + ...erated_device_manager_list_devices_sync.py | 53 + ...ger_modify_cloud_to_device_config_async.py | 53 + ...ager_modify_cloud_to_device_config_sync.py | 53 + ...ce_manager_send_command_to_device_async.py | 53 + ...ice_manager_send_command_to_device_sync.py | 53 + ...ted_device_manager_set_iam_policy_async.py | 53 + ...ated_device_manager_set_iam_policy_sync.py | 53 + ...vice_manager_test_iam_permissions_async.py | 54 + ...evice_manager_test_iam_permissions_sync.py | 54 + ...anager_unbind_device_from_gateway_async.py | 54 + ...manager_unbind_device_from_gateway_sync.py | 54 + ...ated_device_manager_update_device_async.py | 51 + ...ce_manager_update_device_registry_async.py | 51 + ...ice_manager_update_device_registry_sync.py | 51 + ...rated_device_manager_update_device_sync.py | 51 + .../snippet_metadata_google.cloud.iot.v1.json | 3158 +++++ .../v1/scripts/fixup_iot_v1_keywords.py | 194 + owl-bot-staging/v1/setup.py | 91 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.7.txt | 10 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../v1/tests/unit/gapic/iot_v1/__init__.py | 16 + .../unit/gapic/iot_v1/test_device_manager.py | 10954 ++++++++++++++++ 83 files changed, 29402 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/.flake8 create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/docs/iot_v1/device_manager.rst create mode 100644 owl-bot-staging/v1/docs/iot_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/iot_v1/types.rst create mode 100644 owl-bot-staging/v1/google/cloud/iot/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/iot/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/iot/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/client.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/rest.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/types/device_manager.py create mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/types/resources.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.iot.v1.json create mode 100644 owl-bot-staging/v1/scripts/fixup_iot_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/iot_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/iot_v1/test_device_manager.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 00000000..75633d09 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/iot/__init__.py + google/cloud/iot/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/v1/.flake8 b/owl-bot-staging/v1/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 00000000..defad235 --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/iot *.py +recursive-include google/cloud/iot_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 00000000..142d2530 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Iot 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 Cloud Iot 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/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 00000000..d1fe3f41 --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-iot 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-cloud-iot" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud 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-cloud-iot-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-cloud-iot.tex", + u"google-cloud-iot 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-cloud-iot", + u"Google Cloud Iot 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-cloud-iot", + u"google-cloud-iot Documentation", + author, + "google-cloud-iot", + "GAPIC library for Google Cloud Iot 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/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 00000000..c503603d --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + iot_v1/services + iot_v1/types diff --git a/owl-bot-staging/v1/docs/iot_v1/device_manager.rst b/owl-bot-staging/v1/docs/iot_v1/device_manager.rst new file mode 100644 index 00000000..bc4660d9 --- /dev/null +++ b/owl-bot-staging/v1/docs/iot_v1/device_manager.rst @@ -0,0 +1,10 @@ +DeviceManager +------------------------------- + +.. automodule:: google.cloud.iot_v1.services.device_manager + :members: + :inherited-members: + +.. automodule:: google.cloud.iot_v1.services.device_manager.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/iot_v1/services.rst b/owl-bot-staging/v1/docs/iot_v1/services.rst new file mode 100644 index 00000000..64ed529c --- /dev/null +++ b/owl-bot-staging/v1/docs/iot_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Iot v1 API +==================================== +.. toctree:: + :maxdepth: 2 + + device_manager diff --git a/owl-bot-staging/v1/docs/iot_v1/types.rst b/owl-bot-staging/v1/docs/iot_v1/types.rst new file mode 100644 index 00000000..94e5a628 --- /dev/null +++ b/owl-bot-staging/v1/docs/iot_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Iot v1 API +================================= + +.. automodule:: google.cloud.iot_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/iot/__init__.py b/owl-bot-staging/v1/google/cloud/iot/__init__.py new file mode 100644 index 00000000..d8abda36 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot/__init__.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.iot import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.iot_v1.services.device_manager.client import DeviceManagerClient +from google.cloud.iot_v1.services.device_manager.async_client import DeviceManagerAsyncClient + +from google.cloud.iot_v1.types.device_manager import BindDeviceToGatewayRequest +from google.cloud.iot_v1.types.device_manager import BindDeviceToGatewayResponse +from google.cloud.iot_v1.types.device_manager import CreateDeviceRegistryRequest +from google.cloud.iot_v1.types.device_manager import CreateDeviceRequest +from google.cloud.iot_v1.types.device_manager import DeleteDeviceRegistryRequest +from google.cloud.iot_v1.types.device_manager import DeleteDeviceRequest +from google.cloud.iot_v1.types.device_manager import GatewayListOptions +from google.cloud.iot_v1.types.device_manager import GetDeviceRegistryRequest +from google.cloud.iot_v1.types.device_manager import GetDeviceRequest +from google.cloud.iot_v1.types.device_manager import ListDeviceConfigVersionsRequest +from google.cloud.iot_v1.types.device_manager import ListDeviceConfigVersionsResponse +from google.cloud.iot_v1.types.device_manager import ListDeviceRegistriesRequest +from google.cloud.iot_v1.types.device_manager import ListDeviceRegistriesResponse +from google.cloud.iot_v1.types.device_manager import ListDevicesRequest +from google.cloud.iot_v1.types.device_manager import ListDevicesResponse +from google.cloud.iot_v1.types.device_manager import ListDeviceStatesRequest +from google.cloud.iot_v1.types.device_manager import ListDeviceStatesResponse +from google.cloud.iot_v1.types.device_manager import ModifyCloudToDeviceConfigRequest +from google.cloud.iot_v1.types.device_manager import SendCommandToDeviceRequest +from google.cloud.iot_v1.types.device_manager import SendCommandToDeviceResponse +from google.cloud.iot_v1.types.device_manager import UnbindDeviceFromGatewayRequest +from google.cloud.iot_v1.types.device_manager import UnbindDeviceFromGatewayResponse +from google.cloud.iot_v1.types.device_manager import UpdateDeviceRegistryRequest +from google.cloud.iot_v1.types.device_manager import UpdateDeviceRequest +from google.cloud.iot_v1.types.resources import Device +from google.cloud.iot_v1.types.resources import DeviceConfig +from google.cloud.iot_v1.types.resources import DeviceCredential +from google.cloud.iot_v1.types.resources import DeviceRegistry +from google.cloud.iot_v1.types.resources import DeviceState +from google.cloud.iot_v1.types.resources import EventNotificationConfig +from google.cloud.iot_v1.types.resources import GatewayConfig +from google.cloud.iot_v1.types.resources import HttpConfig +from google.cloud.iot_v1.types.resources import MqttConfig +from google.cloud.iot_v1.types.resources import PublicKeyCertificate +from google.cloud.iot_v1.types.resources import PublicKeyCredential +from google.cloud.iot_v1.types.resources import RegistryCredential +from google.cloud.iot_v1.types.resources import StateNotificationConfig +from google.cloud.iot_v1.types.resources import X509CertificateDetails +from google.cloud.iot_v1.types.resources import GatewayAuthMethod +from google.cloud.iot_v1.types.resources import GatewayType +from google.cloud.iot_v1.types.resources import HttpState +from google.cloud.iot_v1.types.resources import LogLevel +from google.cloud.iot_v1.types.resources import MqttState +from google.cloud.iot_v1.types.resources import PublicKeyCertificateFormat +from google.cloud.iot_v1.types.resources import PublicKeyFormat + +__all__ = ('DeviceManagerClient', + 'DeviceManagerAsyncClient', + 'BindDeviceToGatewayRequest', + 'BindDeviceToGatewayResponse', + 'CreateDeviceRegistryRequest', + 'CreateDeviceRequest', + 'DeleteDeviceRegistryRequest', + 'DeleteDeviceRequest', + 'GatewayListOptions', + 'GetDeviceRegistryRequest', + 'GetDeviceRequest', + 'ListDeviceConfigVersionsRequest', + 'ListDeviceConfigVersionsResponse', + 'ListDeviceRegistriesRequest', + 'ListDeviceRegistriesResponse', + 'ListDevicesRequest', + 'ListDevicesResponse', + 'ListDeviceStatesRequest', + 'ListDeviceStatesResponse', + 'ModifyCloudToDeviceConfigRequest', + 'SendCommandToDeviceRequest', + 'SendCommandToDeviceResponse', + 'UnbindDeviceFromGatewayRequest', + 'UnbindDeviceFromGatewayResponse', + 'UpdateDeviceRegistryRequest', + 'UpdateDeviceRequest', + 'Device', + 'DeviceConfig', + 'DeviceCredential', + 'DeviceRegistry', + 'DeviceState', + 'EventNotificationConfig', + 'GatewayConfig', + 'HttpConfig', + 'MqttConfig', + 'PublicKeyCertificate', + 'PublicKeyCredential', + 'RegistryCredential', + 'StateNotificationConfig', + 'X509CertificateDetails', + 'GatewayAuthMethod', + 'GatewayType', + 'HttpState', + 'LogLevel', + 'MqttState', + 'PublicKeyCertificateFormat', + 'PublicKeyFormat', +) diff --git a/owl-bot-staging/v1/google/cloud/iot/gapic_version.py b/owl-bot-staging/v1/google/cloud/iot/gapic_version.py new file mode 100644 index 00000000..405b1ceb --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/iot/py.typed b/owl-bot-staging/v1/google/cloud/iot/py.typed new file mode 100644 index 00000000..d89d40c8 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iot package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/__init__.py b/owl-bot-staging/v1/google/cloud/iot_v1/__init__.py new file mode 100644 index 00000000..a07ced25 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/__init__.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.cloud.iot_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.device_manager import DeviceManagerClient +from .services.device_manager import DeviceManagerAsyncClient + +from .types.device_manager import BindDeviceToGatewayRequest +from .types.device_manager import BindDeviceToGatewayResponse +from .types.device_manager import CreateDeviceRegistryRequest +from .types.device_manager import CreateDeviceRequest +from .types.device_manager import DeleteDeviceRegistryRequest +from .types.device_manager import DeleteDeviceRequest +from .types.device_manager import GatewayListOptions +from .types.device_manager import GetDeviceRegistryRequest +from .types.device_manager import GetDeviceRequest +from .types.device_manager import ListDeviceConfigVersionsRequest +from .types.device_manager import ListDeviceConfigVersionsResponse +from .types.device_manager import ListDeviceRegistriesRequest +from .types.device_manager import ListDeviceRegistriesResponse +from .types.device_manager import ListDevicesRequest +from .types.device_manager import ListDevicesResponse +from .types.device_manager import ListDeviceStatesRequest +from .types.device_manager import ListDeviceStatesResponse +from .types.device_manager import ModifyCloudToDeviceConfigRequest +from .types.device_manager import SendCommandToDeviceRequest +from .types.device_manager import SendCommandToDeviceResponse +from .types.device_manager import UnbindDeviceFromGatewayRequest +from .types.device_manager import UnbindDeviceFromGatewayResponse +from .types.device_manager import UpdateDeviceRegistryRequest +from .types.device_manager import UpdateDeviceRequest +from .types.resources import Device +from .types.resources import DeviceConfig +from .types.resources import DeviceCredential +from .types.resources import DeviceRegistry +from .types.resources import DeviceState +from .types.resources import EventNotificationConfig +from .types.resources import GatewayConfig +from .types.resources import HttpConfig +from .types.resources import MqttConfig +from .types.resources import PublicKeyCertificate +from .types.resources import PublicKeyCredential +from .types.resources import RegistryCredential +from .types.resources import StateNotificationConfig +from .types.resources import X509CertificateDetails +from .types.resources import GatewayAuthMethod +from .types.resources import GatewayType +from .types.resources import HttpState +from .types.resources import LogLevel +from .types.resources import MqttState +from .types.resources import PublicKeyCertificateFormat +from .types.resources import PublicKeyFormat + +__all__ = ( + 'DeviceManagerAsyncClient', +'BindDeviceToGatewayRequest', +'BindDeviceToGatewayResponse', +'CreateDeviceRegistryRequest', +'CreateDeviceRequest', +'DeleteDeviceRegistryRequest', +'DeleteDeviceRequest', +'Device', +'DeviceConfig', +'DeviceCredential', +'DeviceManagerClient', +'DeviceRegistry', +'DeviceState', +'EventNotificationConfig', +'GatewayAuthMethod', +'GatewayConfig', +'GatewayListOptions', +'GatewayType', +'GetDeviceRegistryRequest', +'GetDeviceRequest', +'HttpConfig', +'HttpState', +'ListDeviceConfigVersionsRequest', +'ListDeviceConfigVersionsResponse', +'ListDeviceRegistriesRequest', +'ListDeviceRegistriesResponse', +'ListDeviceStatesRequest', +'ListDeviceStatesResponse', +'ListDevicesRequest', +'ListDevicesResponse', +'LogLevel', +'ModifyCloudToDeviceConfigRequest', +'MqttConfig', +'MqttState', +'PublicKeyCertificate', +'PublicKeyCertificateFormat', +'PublicKeyCredential', +'PublicKeyFormat', +'RegistryCredential', +'SendCommandToDeviceRequest', +'SendCommandToDeviceResponse', +'StateNotificationConfig', +'UnbindDeviceFromGatewayRequest', +'UnbindDeviceFromGatewayResponse', +'UpdateDeviceRegistryRequest', +'UpdateDeviceRequest', +'X509CertificateDetails', +) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/iot_v1/gapic_metadata.json new file mode 100644 index 00000000..b06b7059 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/gapic_metadata.json @@ -0,0 +1,313 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.iot_v1", + "protoPackage": "google.cloud.iot.v1", + "schema": "1.0", + "services": { + "DeviceManager": { + "clients": { + "grpc": { + "libraryClient": "DeviceManagerClient", + "rpcs": { + "BindDeviceToGateway": { + "methods": [ + "bind_device_to_gateway" + ] + }, + "CreateDevice": { + "methods": [ + "create_device" + ] + }, + "CreateDeviceRegistry": { + "methods": [ + "create_device_registry" + ] + }, + "DeleteDevice": { + "methods": [ + "delete_device" + ] + }, + "DeleteDeviceRegistry": { + "methods": [ + "delete_device_registry" + ] + }, + "GetDevice": { + "methods": [ + "get_device" + ] + }, + "GetDeviceRegistry": { + "methods": [ + "get_device_registry" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListDeviceConfigVersions": { + "methods": [ + "list_device_config_versions" + ] + }, + "ListDeviceRegistries": { + "methods": [ + "list_device_registries" + ] + }, + "ListDeviceStates": { + "methods": [ + "list_device_states" + ] + }, + "ListDevices": { + "methods": [ + "list_devices" + ] + }, + "ModifyCloudToDeviceConfig": { + "methods": [ + "modify_cloud_to_device_config" + ] + }, + "SendCommandToDevice": { + "methods": [ + "send_command_to_device" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UnbindDeviceFromGateway": { + "methods": [ + "unbind_device_from_gateway" + ] + }, + "UpdateDevice": { + "methods": [ + "update_device" + ] + }, + "UpdateDeviceRegistry": { + "methods": [ + "update_device_registry" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DeviceManagerAsyncClient", + "rpcs": { + "BindDeviceToGateway": { + "methods": [ + "bind_device_to_gateway" + ] + }, + "CreateDevice": { + "methods": [ + "create_device" + ] + }, + "CreateDeviceRegistry": { + "methods": [ + "create_device_registry" + ] + }, + "DeleteDevice": { + "methods": [ + "delete_device" + ] + }, + "DeleteDeviceRegistry": { + "methods": [ + "delete_device_registry" + ] + }, + "GetDevice": { + "methods": [ + "get_device" + ] + }, + "GetDeviceRegistry": { + "methods": [ + "get_device_registry" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListDeviceConfigVersions": { + "methods": [ + "list_device_config_versions" + ] + }, + "ListDeviceRegistries": { + "methods": [ + "list_device_registries" + ] + }, + "ListDeviceStates": { + "methods": [ + "list_device_states" + ] + }, + "ListDevices": { + "methods": [ + "list_devices" + ] + }, + "ModifyCloudToDeviceConfig": { + "methods": [ + "modify_cloud_to_device_config" + ] + }, + "SendCommandToDevice": { + "methods": [ + "send_command_to_device" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UnbindDeviceFromGateway": { + "methods": [ + "unbind_device_from_gateway" + ] + }, + "UpdateDevice": { + "methods": [ + "update_device" + ] + }, + "UpdateDeviceRegistry": { + "methods": [ + "update_device_registry" + ] + } + } + }, + "rest": { + "libraryClient": "DeviceManagerClient", + "rpcs": { + "BindDeviceToGateway": { + "methods": [ + "bind_device_to_gateway" + ] + }, + "CreateDevice": { + "methods": [ + "create_device" + ] + }, + "CreateDeviceRegistry": { + "methods": [ + "create_device_registry" + ] + }, + "DeleteDevice": { + "methods": [ + "delete_device" + ] + }, + "DeleteDeviceRegistry": { + "methods": [ + "delete_device_registry" + ] + }, + "GetDevice": { + "methods": [ + "get_device" + ] + }, + "GetDeviceRegistry": { + "methods": [ + "get_device_registry" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "ListDeviceConfigVersions": { + "methods": [ + "list_device_config_versions" + ] + }, + "ListDeviceRegistries": { + "methods": [ + "list_device_registries" + ] + }, + "ListDeviceStates": { + "methods": [ + "list_device_states" + ] + }, + "ListDevices": { + "methods": [ + "list_devices" + ] + }, + "ModifyCloudToDeviceConfig": { + "methods": [ + "modify_cloud_to_device_config" + ] + }, + "SendCommandToDevice": { + "methods": [ + "send_command_to_device" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UnbindDeviceFromGateway": { + "methods": [ + "unbind_device_from_gateway" + ] + }, + "UpdateDevice": { + "methods": [ + "update_device" + ] + }, + "UpdateDeviceRegistry": { + "methods": [ + "update_device_registry" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/iot_v1/gapic_version.py new file mode 100644 index 00000000..405b1ceb --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/py.typed b/owl-bot-staging/v1/google/cloud/iot_v1/py.typed new file mode 100644 index 00000000..d89d40c8 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iot package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/__init__.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/__init__.py new file mode 100644 index 00000000..da885f72 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DeviceManagerClient +from .async_client import DeviceManagerAsyncClient + +__all__ = ( + 'DeviceManagerClient', + 'DeviceManagerAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/async_client.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/async_client.py new file mode 100644 index 00000000..345b255d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/async_client.py @@ -0,0 +1,2477 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.iot_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 as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.iot_v1.services.device_manager import pagers +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import DeviceManagerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DeviceManagerGrpcAsyncIOTransport +from .client import DeviceManagerClient + + +class DeviceManagerAsyncClient: + """Internet of Things (IoT) service. Securely connect and manage + IoT devices. + """ + + _client: DeviceManagerClient + + DEFAULT_ENDPOINT = DeviceManagerClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DeviceManagerClient.DEFAULT_MTLS_ENDPOINT + + device_path = staticmethod(DeviceManagerClient.device_path) + parse_device_path = staticmethod(DeviceManagerClient.parse_device_path) + registry_path = staticmethod(DeviceManagerClient.registry_path) + parse_registry_path = staticmethod(DeviceManagerClient.parse_registry_path) + common_billing_account_path = staticmethod(DeviceManagerClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DeviceManagerClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DeviceManagerClient.common_folder_path) + parse_common_folder_path = staticmethod(DeviceManagerClient.parse_common_folder_path) + common_organization_path = staticmethod(DeviceManagerClient.common_organization_path) + parse_common_organization_path = staticmethod(DeviceManagerClient.parse_common_organization_path) + common_project_path = staticmethod(DeviceManagerClient.common_project_path) + parse_common_project_path = staticmethod(DeviceManagerClient.parse_common_project_path) + common_location_path = staticmethod(DeviceManagerClient.common_location_path) + parse_common_location_path = staticmethod(DeviceManagerClient.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: + DeviceManagerAsyncClient: The constructed client. + """ + return DeviceManagerClient.from_service_account_info.__func__(DeviceManagerAsyncClient, 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: + DeviceManagerAsyncClient: The constructed client. + """ + return DeviceManagerClient.from_service_account_file.__func__(DeviceManagerAsyncClient, 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 DeviceManagerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DeviceManagerTransport: + """Returns the transport used by the client instance. + + Returns: + DeviceManagerTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DeviceManagerClient).get_transport_class, type(DeviceManagerClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DeviceManagerTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the device manager client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.DeviceManagerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DeviceManagerClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_device_registry(self, + request: Optional[Union[device_manager.CreateDeviceRegistryRequest, dict]] = None, + *, + parent: Optional[str] = None, + device_registry: Optional[resources.DeviceRegistry] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Creates a device registry that contains devices. + + .. 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.cloud import iot_v1 + + async def sample_create_device_registry(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.CreateDeviceRegistryRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_device_registry(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.CreateDeviceRegistryRequest, dict]]): + The request object. Request for ``CreateDeviceRegistry``. + parent (:class:`str`): + Required. The project and cloud region where this device + registry must be created. For example, + ``projects/example-project/locations/us-central1``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_registry (:class:`google.cloud.iot_v1.types.DeviceRegistry`): + Required. The device registry. The field ``name`` must + be empty. The server will generate that field from the + device registry ``id`` provided and the ``parent`` + field. + + This corresponds to the ``device_registry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.DeviceRegistry: + A container for a group of devices. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, device_registry]) + 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.") + + request = device_manager.CreateDeviceRegistryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if device_registry is not None: + request.device_registry = device_registry + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_device_registry, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_device_registry(self, + request: Optional[Union[device_manager.GetDeviceRegistryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Gets a device registry configuration. + + .. 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.cloud import iot_v1 + + async def sample_get_device_registry(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.GetDeviceRegistryRequest( + name="name_value", + ) + + # Make the request + response = await client.get_device_registry(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.GetDeviceRegistryRequest, dict]]): + The request object. Request for ``GetDeviceRegistry``. + name (:class:`str`): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.DeviceRegistry: + A container for a group of devices. + """ + # 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.") + + request = device_manager.GetDeviceRegistryRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_device_registry, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_device_registry(self, + request: Optional[Union[device_manager.UpdateDeviceRegistryRequest, dict]] = None, + *, + device_registry: Optional[resources.DeviceRegistry] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Updates a device registry configuration. + + .. 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.cloud import iot_v1 + + async def sample_update_device_registry(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.UpdateDeviceRegistryRequest( + ) + + # Make the request + response = await client.update_device_registry(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.UpdateDeviceRegistryRequest, dict]]): + The request object. Request for ``UpdateDeviceRegistry``. + device_registry (:class:`google.cloud.iot_v1.types.DeviceRegistry`): + Required. The new values for the device registry. The + ``id`` field must be empty, and the ``name`` field must + indicate the path of the resource. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``device_registry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Only updates the ``device_registry`` fields + indicated by this mask. The field mask must not be + empty, and it must not contain fields that are immutable + or only set by the server. Mutable top-level fields: + ``event_notification_config``, ``http_config``, + ``mqtt_config``, and ``state_notification_config``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.DeviceRegistry: + A container for a group of devices. + """ + # 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([device_registry, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = device_manager.UpdateDeviceRegistryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if device_registry is not None: + request.device_registry = device_registry + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_device_registry, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("device_registry.name", request.device_registry.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_device_registry(self, + request: Optional[Union[device_manager.DeleteDeviceRegistryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a device registry configuration. + + .. 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.cloud import iot_v1 + + async def sample_delete_device_registry(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.DeleteDeviceRegistryRequest( + name="name_value", + ) + + # Make the request + await client.delete_device_registry(request=request) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.DeleteDeviceRegistryRequest, dict]]): + The request object. Request for ``DeleteDeviceRegistry``. + name (:class:`str`): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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.") + + request = device_manager.DeleteDeviceRegistryRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_device_registry, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_device_registries(self, + request: Optional[Union[device_manager.ListDeviceRegistriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDeviceRegistriesAsyncPager: + r"""Lists device registries. + + .. 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.cloud import iot_v1 + + async def sample_list_device_registries(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceRegistriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_device_registries(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.ListDeviceRegistriesRequest, dict]]): + The request object. Request for ``ListDeviceRegistries``. + parent (:class:`str`): + Required. The project and cloud region path. For + example, + ``projects/example-project/locations/us-central1``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.services.device_manager.pagers.ListDeviceRegistriesAsyncPager: + Response for ListDeviceRegistries. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = device_manager.ListDeviceRegistriesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_device_registries, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDeviceRegistriesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_device(self, + request: Optional[Union[device_manager.CreateDeviceRequest, dict]] = None, + *, + parent: Optional[str] = None, + device: Optional[resources.Device] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Creates a device in a device registry. + + .. 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.cloud import iot_v1 + + async def sample_create_device(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.CreateDeviceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_device(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.CreateDeviceRequest, dict]]): + The request object. Request for ``CreateDevice``. + parent (:class:`str`): + Required. The name of the device registry where this + device should be created. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device (:class:`google.cloud.iot_v1.types.Device`): + Required. The device registration details. The field + ``name`` must be empty. The server generates ``name`` + from the device registry ``id`` and the ``parent`` + field. + + This corresponds to the ``device`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.Device: + The device resource. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, device]) + 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.") + + request = device_manager.CreateDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if device is not None: + request.device = device + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_device, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_device(self, + request: Optional[Union[device_manager.GetDeviceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Gets details about a device. + + .. 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.cloud import iot_v1 + + async def sample_get_device(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.GetDeviceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_device(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.GetDeviceRequest, dict]]): + The request object. Request for ``GetDevice``. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.Device: + The device resource. + """ + # 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.") + + request = device_manager.GetDeviceRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_device, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_device(self, + request: Optional[Union[device_manager.UpdateDeviceRequest, dict]] = None, + *, + device: Optional[resources.Device] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Updates a device. + + .. 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.cloud import iot_v1 + + async def sample_update_device(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.UpdateDeviceRequest( + ) + + # Make the request + response = await client.update_device(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.UpdateDeviceRequest, dict]]): + The request object. Request for ``UpdateDevice``. + device (:class:`google.cloud.iot_v1.types.Device`): + Required. The new values for the device. The ``id`` and + ``num_id`` fields must be empty, and the field ``name`` + must specify the name path. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\ or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``device`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Only updates the ``device`` fields indicated + by this mask. The field mask must not be empty, and it + must not contain fields that are immutable or only set + by the server. Mutable top-level fields: + ``credentials``, ``blocked``, and ``metadata`` + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.Device: + The device resource. + """ + # 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([device, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = device_manager.UpdateDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if device is not None: + request.device = device + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_device, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("device.name", request.device.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_device(self, + request: Optional[Union[device_manager.DeleteDeviceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a device. + + .. 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.cloud import iot_v1 + + async def sample_delete_device(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.DeleteDeviceRequest( + name="name_value", + ) + + # Make the request + await client.delete_device(request=request) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.DeleteDeviceRequest, dict]]): + The request object. Request for ``DeleteDevice``. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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.") + + request = device_manager.DeleteDeviceRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_device, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_devices(self, + request: Optional[Union[device_manager.ListDevicesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDevicesAsyncPager: + r"""List devices in a device registry. + + .. 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.cloud import iot_v1 + + async def sample_list_devices(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.ListDevicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_devices(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.ListDevicesRequest, dict]]): + The request object. Request for ``ListDevices``. + parent (:class:`str`): + Required. The device registry path. Required. For + example, + ``projects/my-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.services.device_manager.pagers.ListDevicesAsyncPager: + Response for ListDevices. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = device_manager.ListDevicesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_devices, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDevicesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def modify_cloud_to_device_config(self, + request: Optional[Union[device_manager.ModifyCloudToDeviceConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + binary_data: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceConfig: + r"""Modifies the configuration for the device, which is + eventually sent from the Cloud IoT Core servers. Returns + the modified configuration version and its metadata. + + .. 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.cloud import iot_v1 + + async def sample_modify_cloud_to_device_config(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.ModifyCloudToDeviceConfigRequest( + name="name_value", + binary_data=b'binary_data_blob', + ) + + # Make the request + response = await client.modify_cloud_to_device_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.ModifyCloudToDeviceConfigRequest, dict]]): + The request object. Request for ``ModifyCloudToDeviceConfig``. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + binary_data (:class:`bytes`): + Required. The configuration data for + the device. + + This corresponds to the ``binary_data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.DeviceConfig: + The device configuration. Eventually + delivered to devices. + + """ + # 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, binary_data]) + 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.") + + request = device_manager.ModifyCloudToDeviceConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if binary_data is not None: + request.binary_data = binary_data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.modify_cloud_to_device_config, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_device_config_versions(self, + request: Optional[Union[device_manager.ListDeviceConfigVersionsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.ListDeviceConfigVersionsResponse: + r"""Lists the last few versions of the device + configuration in descending order (i.e.: newest first). + + .. 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.cloud import iot_v1 + + async def sample_list_device_config_versions(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceConfigVersionsRequest( + name="name_value", + ) + + # Make the request + response = await client.list_device_config_versions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.ListDeviceConfigVersionsRequest, dict]]): + The request object. Request for ``ListDeviceConfigVersions``. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.ListDeviceConfigVersionsResponse: + Response for ListDeviceConfigVersions. + """ + # 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.") + + request = device_manager.ListDeviceConfigVersionsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_device_config_versions, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_device_states(self, + request: Optional[Union[device_manager.ListDeviceStatesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.ListDeviceStatesResponse: + r"""Lists the last few versions of the device state in + descending order (i.e.: newest first). + + .. 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.cloud import iot_v1 + + async def sample_list_device_states(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceStatesRequest( + name="name_value", + ) + + # Make the request + response = await client.list_device_states(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.ListDeviceStatesRequest, dict]]): + The request object. Request for ``ListDeviceStates``. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.ListDeviceStatesResponse: + Response for ListDeviceStates. + """ + # 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.") + + request = device_manager.ListDeviceStatesRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_device_states, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy on the specified + resource. Replaces any existing policy. + + .. 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.cloud import iot_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": [ "user:eve@example.com" ], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **YAML example:** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # 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([resource]) + 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.") + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy for a resource. + Returns an empty policy if the resource exists and does + not have a policy set. + + .. 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.cloud import iot_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": [ "user:eve@example.com" ], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **YAML example:** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # 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([resource]) + 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.") + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns permissions that a caller has on the specified resource. + If the resource does not exist, this will return an empty set of + permissions, not a NOT_FOUND error. + + .. 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.cloud import iot_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # 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([resource, permissions]) + 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.") + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def send_command_to_device(self, + request: Optional[Union[device_manager.SendCommandToDeviceRequest, dict]] = None, + *, + name: Optional[str] = None, + binary_data: Optional[bytes] = None, + subfolder: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.SendCommandToDeviceResponse: + r"""Sends a command to the specified device. In order for a device + to be able to receive commands, it must: + + 1) be connected to Cloud IoT Core using the MQTT protocol, and + 2) be subscribed to the group of MQTT topics specified by + /devices/{device-id}/commands/#. This subscription will + receive commands at the top-level topic + /devices/{device-id}/commands as well as commands for + subfolders, like /devices/{device-id}/commands/subfolder. + Note that subscribing to specific subfolders is not + supported. If the command could not be delivered to the + device, this method will return an error; in particular, if + the device is not subscribed, this method will return + FAILED_PRECONDITION. Otherwise, this method will return OK. + If the subscription is QoS 1, at least once delivery will be + guaranteed; for QoS 0, no acknowledgment will be expected + from the device. + + .. 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.cloud import iot_v1 + + async def sample_send_command_to_device(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.SendCommandToDeviceRequest( + name="name_value", + binary_data=b'binary_data_blob', + ) + + # Make the request + response = await client.send_command_to_device(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.SendCommandToDeviceRequest, dict]]): + The request object. Request for ``SendCommandToDevice``. + name (:class:`str`): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + binary_data (:class:`bytes`): + Required. The command data to send to + the device. + + This corresponds to the ``binary_data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + subfolder (:class:`str`): + Optional subfolder for the command. + If empty, the command will be delivered + to the /devices/{device-id}/commands + topic, otherwise it will be delivered to + the + /devices/{device-id}/commands/{subfolder} + topic. Multi-level subfolders are + allowed. This field must not have more + than 256 characters, and must not + contain any MQTT wildcards ("+" or "#") + or null characters. + + This corresponds to the ``subfolder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.SendCommandToDeviceResponse: + Response for SendCommandToDevice. + """ + # 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, binary_data, subfolder]) + 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.") + + request = device_manager.SendCommandToDeviceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if binary_data is not None: + request.binary_data = binary_data + if subfolder is not None: + request.subfolder = subfolder + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.send_command_to_device, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def bind_device_to_gateway(self, + request: Optional[Union[device_manager.BindDeviceToGatewayRequest, dict]] = None, + *, + parent: Optional[str] = None, + gateway_id: Optional[str] = None, + device_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.BindDeviceToGatewayResponse: + r"""Associates the device with the gateway. + + .. 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.cloud import iot_v1 + + async def sample_bind_device_to_gateway(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.BindDeviceToGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Make the request + response = await client.bind_device_to_gateway(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.BindDeviceToGatewayRequest, dict]]): + The request object. Request for ``BindDeviceToGateway``. + parent (:class:`str`): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway_id (:class:`str`): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + + This corresponds to the ``gateway_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_id (:class:`str`): + Required. The device to associate with the specified + gateway. The value of ``device_id`` can be either the + device numeric ID or the user-defined device identifier. + + This corresponds to the ``device_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.BindDeviceToGatewayResponse: + Response for BindDeviceToGateway. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, gateway_id, device_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = device_manager.BindDeviceToGatewayRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if gateway_id is not None: + request.gateway_id = gateway_id + if device_id is not None: + request.device_id = device_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.bind_device_to_gateway, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def unbind_device_from_gateway(self, + request: Optional[Union[device_manager.UnbindDeviceFromGatewayRequest, dict]] = None, + *, + parent: Optional[str] = None, + gateway_id: Optional[str] = None, + device_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.UnbindDeviceFromGatewayResponse: + r"""Deletes the association between the device and the + gateway. + + .. 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.cloud import iot_v1 + + async def sample_unbind_device_from_gateway(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.UnbindDeviceFromGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Make the request + response = await client.unbind_device_from_gateway(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iot_v1.types.UnbindDeviceFromGatewayRequest, dict]]): + The request object. Request for ``UnbindDeviceFromGateway``. + parent (:class:`str`): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway_id (:class:`str`): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + + This corresponds to the ``gateway_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_id (:class:`str`): + Required. The device to disassociate from the specified + gateway. The value of ``device_id`` can be either the + device numeric ID or the user-defined device identifier. + + This corresponds to the ``device_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.UnbindDeviceFromGatewayResponse: + Response for UnbindDeviceFromGateway. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, gateway_id, device_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = device_manager.UnbindDeviceFromGatewayRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if gateway_id is not None: + request.gateway_id = gateway_id + if device_id is not None: + request.device_id = device_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.unbind_device_from_gateway, + default_timeout=120.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DeviceManagerAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/client.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/client.py new file mode 100644 index 00000000..94ed7be0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/client.py @@ -0,0 +1,2617 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.iot_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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.iot_v1.services.device_manager import pagers +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import DeviceManagerTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DeviceManagerGrpcTransport +from .transports.grpc_asyncio import DeviceManagerGrpcAsyncIOTransport +from .transports.rest import DeviceManagerRestTransport + + +class DeviceManagerClientMeta(type): + """Metaclass for the DeviceManager 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[DeviceManagerTransport]] + _transport_registry["grpc"] = DeviceManagerGrpcTransport + _transport_registry["grpc_asyncio"] = DeviceManagerGrpcAsyncIOTransport + _transport_registry["rest"] = DeviceManagerRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DeviceManagerTransport]: + """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 DeviceManagerClient(metaclass=DeviceManagerClientMeta): + """Internet of Things (IoT) service. Securely connect and manage + IoT devices. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudiot.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DeviceManagerClient: 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: + DeviceManagerClient: 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) -> DeviceManagerTransport: + """Returns the transport used by the client instance. + + Returns: + DeviceManagerTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def device_path(project: str,location: str,registry: str,device: str,) -> str: + """Returns a fully-qualified device string.""" + return "projects/{project}/locations/{location}/registries/{registry}/devices/{device}".format(project=project, location=location, registry=registry, device=device, ) + + @staticmethod + def parse_device_path(path: str) -> Dict[str,str]: + """Parses a device path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/registries/(?P.+?)/devices/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def registry_path(project: str,location: str,registry: str,) -> str: + """Returns a fully-qualified registry string.""" + return "projects/{project}/locations/{location}/registries/{registry}".format(project=project, location=location, registry=registry, ) + + @staticmethod + def parse_registry_path(path: str) -> Dict[str,str]: + """Parses a registry path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/registries/(?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): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DeviceManagerTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the device manager client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, DeviceManagerTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DeviceManagerTransport): + # transport is a DeviceManagerTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_device_registry(self, + request: Optional[Union[device_manager.CreateDeviceRegistryRequest, dict]] = None, + *, + parent: Optional[str] = None, + device_registry: Optional[resources.DeviceRegistry] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Creates a device registry that contains devices. + + .. 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.cloud import iot_v1 + + def sample_create_device_registry(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.CreateDeviceRegistryRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_device_registry(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.CreateDeviceRegistryRequest, dict]): + The request object. Request for ``CreateDeviceRegistry``. + parent (str): + Required. The project and cloud region where this device + registry must be created. For example, + ``projects/example-project/locations/us-central1``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_registry (google.cloud.iot_v1.types.DeviceRegistry): + Required. The device registry. The field ``name`` must + be empty. The server will generate that field from the + device registry ``id`` provided and the ``parent`` + field. + + This corresponds to the ``device_registry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.DeviceRegistry: + A container for a group of devices. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, device_registry]) + 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.CreateDeviceRegistryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.CreateDeviceRegistryRequest): + request = device_manager.CreateDeviceRegistryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if device_registry is not None: + request.device_registry = device_registry + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_device_registry] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_device_registry(self, + request: Optional[Union[device_manager.GetDeviceRegistryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Gets a device registry configuration. + + .. 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.cloud import iot_v1 + + def sample_get_device_registry(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.GetDeviceRegistryRequest( + name="name_value", + ) + + # Make the request + response = client.get_device_registry(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.GetDeviceRegistryRequest, dict]): + The request object. Request for ``GetDeviceRegistry``. + name (str): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.DeviceRegistry: + A container for a group of devices. + """ + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.GetDeviceRegistryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.GetDeviceRegistryRequest): + request = device_manager.GetDeviceRegistryRequest(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_device_registry] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_device_registry(self, + request: Optional[Union[device_manager.UpdateDeviceRegistryRequest, dict]] = None, + *, + device_registry: Optional[resources.DeviceRegistry] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceRegistry: + r"""Updates a device registry configuration. + + .. 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.cloud import iot_v1 + + def sample_update_device_registry(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.UpdateDeviceRegistryRequest( + ) + + # Make the request + response = client.update_device_registry(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.UpdateDeviceRegistryRequest, dict]): + The request object. Request for ``UpdateDeviceRegistry``. + device_registry (google.cloud.iot_v1.types.DeviceRegistry): + Required. The new values for the device registry. The + ``id`` field must be empty, and the ``name`` field must + indicate the path of the resource. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``device_registry`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Only updates the ``device_registry`` fields + indicated by this mask. The field mask must not be + empty, and it must not contain fields that are immutable + or only set by the server. Mutable top-level fields: + ``event_notification_config``, ``http_config``, + ``mqtt_config``, and ``state_notification_config``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.DeviceRegistry: + A container for a group of devices. + """ + # 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([device_registry, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.UpdateDeviceRegistryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.UpdateDeviceRegistryRequest): + request = device_manager.UpdateDeviceRegistryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if device_registry is not None: + request.device_registry = device_registry + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_device_registry] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("device_registry.name", request.device_registry.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_device_registry(self, + request: Optional[Union[device_manager.DeleteDeviceRegistryRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a device registry configuration. + + .. 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.cloud import iot_v1 + + def sample_delete_device_registry(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.DeleteDeviceRegistryRequest( + name="name_value", + ) + + # Make the request + client.delete_device_registry(request=request) + + Args: + request (Union[google.cloud.iot_v1.types.DeleteDeviceRegistryRequest, dict]): + The request object. Request for ``DeleteDeviceRegistry``. + name (str): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.DeleteDeviceRegistryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.DeleteDeviceRegistryRequest): + request = device_manager.DeleteDeviceRegistryRequest(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.delete_device_registry] + + # 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), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_device_registries(self, + request: Optional[Union[device_manager.ListDeviceRegistriesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDeviceRegistriesPager: + r"""Lists device registries. + + .. 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.cloud import iot_v1 + + def sample_list_device_registries(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceRegistriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_device_registries(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.ListDeviceRegistriesRequest, dict]): + The request object. Request for ``ListDeviceRegistries``. + parent (str): + Required. The project and cloud region path. For + example, + ``projects/example-project/locations/us-central1``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.services.device_manager.pagers.ListDeviceRegistriesPager: + Response for ListDeviceRegistries. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.ListDeviceRegistriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.ListDeviceRegistriesRequest): + request = device_manager.ListDeviceRegistriesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_device_registries] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDeviceRegistriesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_device(self, + request: Optional[Union[device_manager.CreateDeviceRequest, dict]] = None, + *, + parent: Optional[str] = None, + device: Optional[resources.Device] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Creates a device in a device registry. + + .. 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.cloud import iot_v1 + + def sample_create_device(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.CreateDeviceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_device(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.CreateDeviceRequest, dict]): + The request object. Request for ``CreateDevice``. + parent (str): + Required. The name of the device registry where this + device should be created. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device (google.cloud.iot_v1.types.Device): + Required. The device registration details. The field + ``name`` must be empty. The server generates ``name`` + from the device registry ``id`` and the ``parent`` + field. + + This corresponds to the ``device`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.Device: + The device resource. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, device]) + 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.CreateDeviceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.CreateDeviceRequest): + request = device_manager.CreateDeviceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if device is not None: + request.device = device + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_device] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_device(self, + request: Optional[Union[device_manager.GetDeviceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Gets details about a device. + + .. 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.cloud import iot_v1 + + def sample_get_device(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.GetDeviceRequest( + name="name_value", + ) + + # Make the request + response = client.get_device(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.GetDeviceRequest, dict]): + The request object. Request for ``GetDevice``. + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.Device: + The device resource. + """ + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.GetDeviceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.GetDeviceRequest): + request = device_manager.GetDeviceRequest(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_device] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_device(self, + request: Optional[Union[device_manager.UpdateDeviceRequest, dict]] = None, + *, + device: Optional[resources.Device] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Device: + r"""Updates a device. + + .. 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.cloud import iot_v1 + + def sample_update_device(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.UpdateDeviceRequest( + ) + + # Make the request + response = client.update_device(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.UpdateDeviceRequest, dict]): + The request object. Request for ``UpdateDevice``. + device (google.cloud.iot_v1.types.Device): + Required. The new values for the device. The ``id`` and + ``num_id`` fields must be empty, and the field ``name`` + must specify the name path. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\ or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``device`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Only updates the ``device`` fields indicated + by this mask. The field mask must not be empty, and it + must not contain fields that are immutable or only set + by the server. Mutable top-level fields: + ``credentials``, ``blocked``, and ``metadata`` + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.Device: + The device resource. + """ + # 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([device, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.UpdateDeviceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.UpdateDeviceRequest): + request = device_manager.UpdateDeviceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if device is not None: + request.device = device + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_device] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("device.name", request.device.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_device(self, + request: Optional[Union[device_manager.DeleteDeviceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a device. + + .. 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.cloud import iot_v1 + + def sample_delete_device(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.DeleteDeviceRequest( + name="name_value", + ) + + # Make the request + client.delete_device(request=request) + + Args: + request (Union[google.cloud.iot_v1.types.DeleteDeviceRequest, dict]): + The request object. Request for ``DeleteDevice``. + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.DeleteDeviceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.DeleteDeviceRequest): + request = device_manager.DeleteDeviceRequest(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.delete_device] + + # 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), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_devices(self, + request: Optional[Union[device_manager.ListDevicesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDevicesPager: + r"""List devices in a device registry. + + .. 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.cloud import iot_v1 + + def sample_list_devices(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.ListDevicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_devices(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.ListDevicesRequest, dict]): + The request object. Request for ``ListDevices``. + parent (str): + Required. The device registry path. Required. For + example, + ``projects/my-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.services.device_manager.pagers.ListDevicesPager: + Response for ListDevices. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.ListDevicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.ListDevicesRequest): + request = device_manager.ListDevicesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_devices] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDevicesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def modify_cloud_to_device_config(self, + request: Optional[Union[device_manager.ModifyCloudToDeviceConfigRequest, dict]] = None, + *, + name: Optional[str] = None, + binary_data: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DeviceConfig: + r"""Modifies the configuration for the device, which is + eventually sent from the Cloud IoT Core servers. Returns + the modified configuration version and its metadata. + + .. 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.cloud import iot_v1 + + def sample_modify_cloud_to_device_config(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.ModifyCloudToDeviceConfigRequest( + name="name_value", + binary_data=b'binary_data_blob', + ) + + # Make the request + response = client.modify_cloud_to_device_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.ModifyCloudToDeviceConfigRequest, dict]): + The request object. Request for ``ModifyCloudToDeviceConfig``. + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + binary_data (bytes): + Required. The configuration data for + the device. + + This corresponds to the ``binary_data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.DeviceConfig: + The device configuration. Eventually + delivered to devices. + + """ + # 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, binary_data]) + 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.ModifyCloudToDeviceConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.ModifyCloudToDeviceConfigRequest): + request = device_manager.ModifyCloudToDeviceConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if binary_data is not None: + request.binary_data = binary_data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.modify_cloud_to_device_config] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_device_config_versions(self, + request: Optional[Union[device_manager.ListDeviceConfigVersionsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.ListDeviceConfigVersionsResponse: + r"""Lists the last few versions of the device + configuration in descending order (i.e.: newest first). + + .. 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.cloud import iot_v1 + + def sample_list_device_config_versions(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceConfigVersionsRequest( + name="name_value", + ) + + # Make the request + response = client.list_device_config_versions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.ListDeviceConfigVersionsRequest, dict]): + The request object. Request for ``ListDeviceConfigVersions``. + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.ListDeviceConfigVersionsResponse: + Response for ListDeviceConfigVersions. + """ + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.ListDeviceConfigVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.ListDeviceConfigVersionsRequest): + request = device_manager.ListDeviceConfigVersionsRequest(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.list_device_config_versions] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_device_states(self, + request: Optional[Union[device_manager.ListDeviceStatesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.ListDeviceStatesResponse: + r"""Lists the last few versions of the device state in + descending order (i.e.: newest first). + + .. 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.cloud import iot_v1 + + def sample_list_device_states(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceStatesRequest( + name="name_value", + ) + + # Make the request + response = client.list_device_states(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.ListDeviceStatesRequest, dict]): + The request object. Request for ``ListDeviceStates``. + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.ListDeviceStatesResponse: + Response for ListDeviceStates. + """ + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.ListDeviceStatesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.ListDeviceStatesRequest): + request = device_manager.ListDeviceStatesRequest(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.list_device_states] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy(self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy on the specified + resource. Replaces any existing policy. + + .. 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.cloud import iot_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": [ "user:eve@example.com" ], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **YAML example:** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # 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([resource]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy(self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy for a resource. + Returns an empty policy if the resource exists and does + not have a policy set. + + .. 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.cloud import iot_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + { + "bindings": [ + { + "role": + "roles/resourcemanager.organizationAdmin", + "members": [ "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + + }, { "role": + "roles/resourcemanager.organizationViewer", + "members": [ "user:eve@example.com" ], + "condition": { "title": "expirable access", + "description": "Does not grant access after + Sep 2020", "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", } } + + ], "etag": "BwWWja0YfJA=", "version": 3 + + } + + **YAML example:** + + bindings: - members: - user:\ mike@example.com - + group:\ admins@example.com - domain:google.com - + serviceAccount:\ my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin - + members: - user:\ eve@example.com role: + roles/resourcemanager.organizationViewer + condition: title: expirable access description: + Does not grant access after Sep 2020 expression: + request.time < + timestamp('2020-10-01T00:00:00.000Z') etag: + BwWWja0YfJA= version: 3 + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # 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([resource]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions(self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns permissions that a caller has on the specified resource. + If the resource does not exist, this will return an empty set of + permissions, not a NOT_FOUND error. + + .. 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.cloud import iot_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # 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([resource, permissions]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def send_command_to_device(self, + request: Optional[Union[device_manager.SendCommandToDeviceRequest, dict]] = None, + *, + name: Optional[str] = None, + binary_data: Optional[bytes] = None, + subfolder: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.SendCommandToDeviceResponse: + r"""Sends a command to the specified device. In order for a device + to be able to receive commands, it must: + + 1) be connected to Cloud IoT Core using the MQTT protocol, and + 2) be subscribed to the group of MQTT topics specified by + /devices/{device-id}/commands/#. This subscription will + receive commands at the top-level topic + /devices/{device-id}/commands as well as commands for + subfolders, like /devices/{device-id}/commands/subfolder. + Note that subscribing to specific subfolders is not + supported. If the command could not be delivered to the + device, this method will return an error; in particular, if + the device is not subscribed, this method will return + FAILED_PRECONDITION. Otherwise, this method will return OK. + If the subscription is QoS 1, at least once delivery will be + guaranteed; for QoS 0, no acknowledgment will be expected + from the device. + + .. 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.cloud import iot_v1 + + def sample_send_command_to_device(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.SendCommandToDeviceRequest( + name="name_value", + binary_data=b'binary_data_blob', + ) + + # Make the request + response = client.send_command_to_device(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.SendCommandToDeviceRequest, dict]): + The request object. Request for ``SendCommandToDevice``. + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + binary_data (bytes): + Required. The command data to send to + the device. + + This corresponds to the ``binary_data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + subfolder (str): + Optional subfolder for the command. + If empty, the command will be delivered + to the /devices/{device-id}/commands + topic, otherwise it will be delivered to + the + /devices/{device-id}/commands/{subfolder} + topic. Multi-level subfolders are + allowed. This field must not have more + than 256 characters, and must not + contain any MQTT wildcards ("+" or "#") + or null characters. + + This corresponds to the ``subfolder`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.SendCommandToDeviceResponse: + Response for SendCommandToDevice. + """ + # 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, binary_data, subfolder]) + 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.SendCommandToDeviceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.SendCommandToDeviceRequest): + request = device_manager.SendCommandToDeviceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if binary_data is not None: + request.binary_data = binary_data + if subfolder is not None: + request.subfolder = subfolder + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.send_command_to_device] + + # 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def bind_device_to_gateway(self, + request: Optional[Union[device_manager.BindDeviceToGatewayRequest, dict]] = None, + *, + parent: Optional[str] = None, + gateway_id: Optional[str] = None, + device_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.BindDeviceToGatewayResponse: + r"""Associates the device with the gateway. + + .. 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.cloud import iot_v1 + + def sample_bind_device_to_gateway(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.BindDeviceToGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Make the request + response = client.bind_device_to_gateway(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.BindDeviceToGatewayRequest, dict]): + The request object. Request for ``BindDeviceToGateway``. + parent (str): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway_id (str): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + + This corresponds to the ``gateway_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_id (str): + Required. The device to associate with the specified + gateway. The value of ``device_id`` can be either the + device numeric ID or the user-defined device identifier. + + This corresponds to the ``device_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.BindDeviceToGatewayResponse: + Response for BindDeviceToGateway. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, gateway_id, device_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.BindDeviceToGatewayRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.BindDeviceToGatewayRequest): + request = device_manager.BindDeviceToGatewayRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if gateway_id is not None: + request.gateway_id = gateway_id + if device_id is not None: + request.device_id = device_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.bind_device_to_gateway] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def unbind_device_from_gateway(self, + request: Optional[Union[device_manager.UnbindDeviceFromGatewayRequest, dict]] = None, + *, + parent: Optional[str] = None, + gateway_id: Optional[str] = None, + device_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> device_manager.UnbindDeviceFromGatewayResponse: + r"""Deletes the association between the device and the + gateway. + + .. 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.cloud import iot_v1 + + def sample_unbind_device_from_gateway(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.UnbindDeviceFromGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Make the request + response = client.unbind_device_from_gateway(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iot_v1.types.UnbindDeviceFromGatewayRequest, dict]): + The request object. Request for ``UnbindDeviceFromGateway``. + parent (str): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + gateway_id (str): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + + This corresponds to the ``gateway_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + device_id (str): + Required. The device to disassociate from the specified + gateway. The value of ``device_id`` can be either the + device numeric ID or the user-defined device identifier. + + This corresponds to the ``device_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iot_v1.types.UnbindDeviceFromGatewayResponse: + Response for UnbindDeviceFromGateway. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, gateway_id, device_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a device_manager.UnbindDeviceFromGatewayRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, device_manager.UnbindDeviceFromGatewayRequest): + request = device_manager.UnbindDeviceFromGatewayRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if gateway_id is not None: + request.gateway_id = gateway_id + if device_id is not None: + request.device_id = device_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.unbind_device_from_gateway] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DeviceManagerClient": + 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__ = ( + "DeviceManagerClient", +) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/pagers.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/pagers.py new file mode 100644 index 00000000..893c9119 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/pagers.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources + + +class ListDeviceRegistriesPager: + """A pager for iterating through ``list_device_registries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iot_v1.types.ListDeviceRegistriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``device_registries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDeviceRegistries`` requests and continue to iterate + through the ``device_registries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iot_v1.types.ListDeviceRegistriesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., device_manager.ListDeviceRegistriesResponse], + request: device_manager.ListDeviceRegistriesRequest, + response: device_manager.ListDeviceRegistriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iot_v1.types.ListDeviceRegistriesRequest): + The initial request object. + response (google.cloud.iot_v1.types.ListDeviceRegistriesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = device_manager.ListDeviceRegistriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[device_manager.ListDeviceRegistriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.DeviceRegistry]: + for page in self.pages: + yield from page.device_registries + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDeviceRegistriesAsyncPager: + """A pager for iterating through ``list_device_registries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iot_v1.types.ListDeviceRegistriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``device_registries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDeviceRegistries`` requests and continue to iterate + through the ``device_registries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iot_v1.types.ListDeviceRegistriesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[device_manager.ListDeviceRegistriesResponse]], + request: device_manager.ListDeviceRegistriesRequest, + response: device_manager.ListDeviceRegistriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iot_v1.types.ListDeviceRegistriesRequest): + The initial request object. + response (google.cloud.iot_v1.types.ListDeviceRegistriesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = device_manager.ListDeviceRegistriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[device_manager.ListDeviceRegistriesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.DeviceRegistry]: + async def async_generator(): + async for page in self.pages: + for response in page.device_registries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDevicesPager: + """A pager for iterating through ``list_devices`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iot_v1.types.ListDevicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``devices`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDevices`` requests and continue to iterate + through the ``devices`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iot_v1.types.ListDevicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., device_manager.ListDevicesResponse], + request: device_manager.ListDevicesRequest, + response: device_manager.ListDevicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iot_v1.types.ListDevicesRequest): + The initial request object. + response (google.cloud.iot_v1.types.ListDevicesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = device_manager.ListDevicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[device_manager.ListDevicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.Device]: + for page in self.pages: + yield from page.devices + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDevicesAsyncPager: + """A pager for iterating through ``list_devices`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iot_v1.types.ListDevicesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``devices`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDevices`` requests and continue to iterate + through the ``devices`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iot_v1.types.ListDevicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[device_manager.ListDevicesResponse]], + request: device_manager.ListDevicesRequest, + response: device_manager.ListDevicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iot_v1.types.ListDevicesRequest): + The initial request object. + response (google.cloud.iot_v1.types.ListDevicesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = device_manager.ListDevicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[device_manager.ListDevicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.Device]: + async def async_generator(): + async for page in self.pages: + for response in page.devices: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/__init__.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/__init__.py new file mode 100644 index 00000000..b346a3de --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DeviceManagerTransport +from .grpc import DeviceManagerGrpcTransport +from .grpc_asyncio import DeviceManagerGrpcAsyncIOTransport +from .rest import DeviceManagerRestTransport +from .rest import DeviceManagerRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DeviceManagerTransport]] +_transport_registry['grpc'] = DeviceManagerGrpcTransport +_transport_registry['grpc_asyncio'] = DeviceManagerGrpcAsyncIOTransport +_transport_registry['rest'] = DeviceManagerRestTransport + +__all__ = ( + 'DeviceManagerTransport', + 'DeviceManagerGrpcTransport', + 'DeviceManagerGrpcAsyncIOTransport', + 'DeviceManagerRestTransport', + 'DeviceManagerRestInterceptor', +) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/base.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/base.py new file mode 100644 index 00000000..98bb5dec --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/base.py @@ -0,0 +1,477 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.cloud.iot_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.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DeviceManagerTransport(abc.ABC): + """Abstract transport class for DeviceManager.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudiot', + ) + + DEFAULT_HOST: str = 'cloudiot.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_device_registry: gapic_v1.method.wrap_method( + self.create_device_registry, + default_timeout=120.0, + client_info=client_info, + ), + self.get_device_registry: gapic_v1.method.wrap_method( + self.get_device_registry, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_device_registry: gapic_v1.method.wrap_method( + self.update_device_registry, + default_timeout=120.0, + client_info=client_info, + ), + self.delete_device_registry: gapic_v1.method.wrap_method( + self.delete_device_registry, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.list_device_registries: gapic_v1.method.wrap_method( + self.list_device_registries, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.create_device: gapic_v1.method.wrap_method( + self.create_device, + default_timeout=120.0, + client_info=client_info, + ), + self.get_device: gapic_v1.method.wrap_method( + self.get_device, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_device: gapic_v1.method.wrap_method( + self.update_device, + default_timeout=120.0, + client_info=client_info, + ), + self.delete_device: gapic_v1.method.wrap_method( + self.delete_device, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.list_devices: gapic_v1.method.wrap_method( + self.list_devices, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.modify_cloud_to_device_config: gapic_v1.method.wrap_method( + self.modify_cloud_to_device_config, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.list_device_config_versions: gapic_v1.method.wrap_method( + self.list_device_config_versions, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.list_device_states: gapic_v1.method.wrap_method( + self.list_device_states, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=120.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=120.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=120.0, + client_info=client_info, + ), + self.send_command_to_device: gapic_v1.method.wrap_method( + self.send_command_to_device, + default_retry=retries.Retry( +initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.bind_device_to_gateway: gapic_v1.method.wrap_method( + self.bind_device_to_gateway, + default_timeout=120.0, + client_info=client_info, + ), + self.unbind_device_from_gateway: gapic_v1.method.wrap_method( + self.unbind_device_from_gateway, + default_timeout=120.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_device_registry(self) -> Callable[ + [device_manager.CreateDeviceRegistryRequest], + Union[ + resources.DeviceRegistry, + Awaitable[resources.DeviceRegistry] + ]]: + raise NotImplementedError() + + @property + def get_device_registry(self) -> Callable[ + [device_manager.GetDeviceRegistryRequest], + Union[ + resources.DeviceRegistry, + Awaitable[resources.DeviceRegistry] + ]]: + raise NotImplementedError() + + @property + def update_device_registry(self) -> Callable[ + [device_manager.UpdateDeviceRegistryRequest], + Union[ + resources.DeviceRegistry, + Awaitable[resources.DeviceRegistry] + ]]: + raise NotImplementedError() + + @property + def delete_device_registry(self) -> Callable[ + [device_manager.DeleteDeviceRegistryRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_device_registries(self) -> Callable[ + [device_manager.ListDeviceRegistriesRequest], + Union[ + device_manager.ListDeviceRegistriesResponse, + Awaitable[device_manager.ListDeviceRegistriesResponse] + ]]: + raise NotImplementedError() + + @property + def create_device(self) -> Callable[ + [device_manager.CreateDeviceRequest], + Union[ + resources.Device, + Awaitable[resources.Device] + ]]: + raise NotImplementedError() + + @property + def get_device(self) -> Callable[ + [device_manager.GetDeviceRequest], + Union[ + resources.Device, + Awaitable[resources.Device] + ]]: + raise NotImplementedError() + + @property + def update_device(self) -> Callable[ + [device_manager.UpdateDeviceRequest], + Union[ + resources.Device, + Awaitable[resources.Device] + ]]: + raise NotImplementedError() + + @property + def delete_device(self) -> Callable[ + [device_manager.DeleteDeviceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_devices(self) -> Callable[ + [device_manager.ListDevicesRequest], + Union[ + device_manager.ListDevicesResponse, + Awaitable[device_manager.ListDevicesResponse] + ]]: + raise NotImplementedError() + + @property + def modify_cloud_to_device_config(self) -> Callable[ + [device_manager.ModifyCloudToDeviceConfigRequest], + Union[ + resources.DeviceConfig, + Awaitable[resources.DeviceConfig] + ]]: + raise NotImplementedError() + + @property + def list_device_config_versions(self) -> Callable[ + [device_manager.ListDeviceConfigVersionsRequest], + Union[ + device_manager.ListDeviceConfigVersionsResponse, + Awaitable[device_manager.ListDeviceConfigVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def list_device_states(self) -> Callable[ + [device_manager.ListDeviceStatesRequest], + Union[ + device_manager.ListDeviceStatesResponse, + Awaitable[device_manager.ListDeviceStatesResponse] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[ + policy_pb2.Policy, + Awaitable[policy_pb2.Policy] + ]]: + raise NotImplementedError() + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def send_command_to_device(self) -> Callable[ + [device_manager.SendCommandToDeviceRequest], + Union[ + device_manager.SendCommandToDeviceResponse, + Awaitable[device_manager.SendCommandToDeviceResponse] + ]]: + raise NotImplementedError() + + @property + def bind_device_to_gateway(self) -> Callable[ + [device_manager.BindDeviceToGatewayRequest], + Union[ + device_manager.BindDeviceToGatewayResponse, + Awaitable[device_manager.BindDeviceToGatewayResponse] + ]]: + raise NotImplementedError() + + @property + def unbind_device_from_gateway(self) -> Callable[ + [device_manager.UnbindDeviceFromGatewayRequest], + Union[ + device_manager.UnbindDeviceFromGatewayResponse, + Awaitable[device_manager.UnbindDeviceFromGatewayResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'DeviceManagerTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc.py new file mode 100644 index 00000000..895558d8 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc.py @@ -0,0 +1,763 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DeviceManagerTransport, DEFAULT_CLIENT_INFO + + +class DeviceManagerGrpcTransport(DeviceManagerTransport): + """gRPC backend transport for DeviceManager. + + Internet of Things (IoT) service. Securely connect and manage + IoT devices. + + 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 = 'cloudiot.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudiot.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_device_registry(self) -> Callable[ + [device_manager.CreateDeviceRegistryRequest], + resources.DeviceRegistry]: + r"""Return a callable for the create device registry method over gRPC. + + Creates a device registry that contains devices. + + Returns: + Callable[[~.CreateDeviceRegistryRequest], + ~.DeviceRegistry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_device_registry' not in self._stubs: + self._stubs['create_device_registry'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/CreateDeviceRegistry', + request_serializer=device_manager.CreateDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs['create_device_registry'] + + @property + def get_device_registry(self) -> Callable[ + [device_manager.GetDeviceRegistryRequest], + resources.DeviceRegistry]: + r"""Return a callable for the get device registry method over gRPC. + + Gets a device registry configuration. + + Returns: + Callable[[~.GetDeviceRegistryRequest], + ~.DeviceRegistry]: + 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_device_registry' not in self._stubs: + self._stubs['get_device_registry'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/GetDeviceRegistry', + request_serializer=device_manager.GetDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs['get_device_registry'] + + @property + def update_device_registry(self) -> Callable[ + [device_manager.UpdateDeviceRegistryRequest], + resources.DeviceRegistry]: + r"""Return a callable for the update device registry method over gRPC. + + Updates a device registry configuration. + + Returns: + Callable[[~.UpdateDeviceRegistryRequest], + ~.DeviceRegistry]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_device_registry' not in self._stubs: + self._stubs['update_device_registry'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/UpdateDeviceRegistry', + request_serializer=device_manager.UpdateDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs['update_device_registry'] + + @property + def delete_device_registry(self) -> Callable[ + [device_manager.DeleteDeviceRegistryRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete device registry method over gRPC. + + Deletes a device registry configuration. + + Returns: + Callable[[~.DeleteDeviceRegistryRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_device_registry' not in self._stubs: + self._stubs['delete_device_registry'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/DeleteDeviceRegistry', + request_serializer=device_manager.DeleteDeviceRegistryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_device_registry'] + + @property + def list_device_registries(self) -> Callable[ + [device_manager.ListDeviceRegistriesRequest], + device_manager.ListDeviceRegistriesResponse]: + r"""Return a callable for the list device registries method over gRPC. + + Lists device registries. + + Returns: + Callable[[~.ListDeviceRegistriesRequest], + ~.ListDeviceRegistriesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_device_registries' not in self._stubs: + self._stubs['list_device_registries'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/ListDeviceRegistries', + request_serializer=device_manager.ListDeviceRegistriesRequest.serialize, + response_deserializer=device_manager.ListDeviceRegistriesResponse.deserialize, + ) + return self._stubs['list_device_registries'] + + @property + def create_device(self) -> Callable[ + [device_manager.CreateDeviceRequest], + resources.Device]: + r"""Return a callable for the create device method over gRPC. + + Creates a device in a device registry. + + Returns: + Callable[[~.CreateDeviceRequest], + ~.Device]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_device' not in self._stubs: + self._stubs['create_device'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/CreateDevice', + request_serializer=device_manager.CreateDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs['create_device'] + + @property + def get_device(self) -> Callable[ + [device_manager.GetDeviceRequest], + resources.Device]: + r"""Return a callable for the get device method over gRPC. + + Gets details about a device. + + Returns: + Callable[[~.GetDeviceRequest], + ~.Device]: + 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_device' not in self._stubs: + self._stubs['get_device'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/GetDevice', + request_serializer=device_manager.GetDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs['get_device'] + + @property + def update_device(self) -> Callable[ + [device_manager.UpdateDeviceRequest], + resources.Device]: + r"""Return a callable for the update device method over gRPC. + + Updates a device. + + Returns: + Callable[[~.UpdateDeviceRequest], + ~.Device]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_device' not in self._stubs: + self._stubs['update_device'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/UpdateDevice', + request_serializer=device_manager.UpdateDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs['update_device'] + + @property + def delete_device(self) -> Callable[ + [device_manager.DeleteDeviceRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete device method over gRPC. + + Deletes a device. + + Returns: + Callable[[~.DeleteDeviceRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_device' not in self._stubs: + self._stubs['delete_device'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/DeleteDevice', + request_serializer=device_manager.DeleteDeviceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_device'] + + @property + def list_devices(self) -> Callable[ + [device_manager.ListDevicesRequest], + device_manager.ListDevicesResponse]: + r"""Return a callable for the list devices method over gRPC. + + List devices in a device registry. + + Returns: + Callable[[~.ListDevicesRequest], + ~.ListDevicesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_devices' not in self._stubs: + self._stubs['list_devices'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/ListDevices', + request_serializer=device_manager.ListDevicesRequest.serialize, + response_deserializer=device_manager.ListDevicesResponse.deserialize, + ) + return self._stubs['list_devices'] + + @property + def modify_cloud_to_device_config(self) -> Callable[ + [device_manager.ModifyCloudToDeviceConfigRequest], + resources.DeviceConfig]: + r"""Return a callable for the modify cloud to device config method over gRPC. + + Modifies the configuration for the device, which is + eventually sent from the Cloud IoT Core servers. Returns + the modified configuration version and its metadata. + + Returns: + Callable[[~.ModifyCloudToDeviceConfigRequest], + ~.DeviceConfig]: + 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 'modify_cloud_to_device_config' not in self._stubs: + self._stubs['modify_cloud_to_device_config'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/ModifyCloudToDeviceConfig', + request_serializer=device_manager.ModifyCloudToDeviceConfigRequest.serialize, + response_deserializer=resources.DeviceConfig.deserialize, + ) + return self._stubs['modify_cloud_to_device_config'] + + @property + def list_device_config_versions(self) -> Callable[ + [device_manager.ListDeviceConfigVersionsRequest], + device_manager.ListDeviceConfigVersionsResponse]: + r"""Return a callable for the list device config versions method over gRPC. + + Lists the last few versions of the device + configuration in descending order (i.e.: newest first). + + Returns: + Callable[[~.ListDeviceConfigVersionsRequest], + ~.ListDeviceConfigVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_device_config_versions' not in self._stubs: + self._stubs['list_device_config_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/ListDeviceConfigVersions', + request_serializer=device_manager.ListDeviceConfigVersionsRequest.serialize, + response_deserializer=device_manager.ListDeviceConfigVersionsResponse.deserialize, + ) + return self._stubs['list_device_config_versions'] + + @property + def list_device_states(self) -> Callable[ + [device_manager.ListDeviceStatesRequest], + device_manager.ListDeviceStatesResponse]: + r"""Return a callable for the list device states method over gRPC. + + Lists the last few versions of the device state in + descending order (i.e.: newest first). + + Returns: + Callable[[~.ListDeviceStatesRequest], + ~.ListDeviceStatesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_device_states' not in self._stubs: + self._stubs['list_device_states'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/ListDeviceStates', + request_serializer=device_manager.ListDeviceStatesRequest.serialize, + response_deserializer=device_manager.ListDeviceStatesResponse.deserialize, + ) + return self._stubs['list_device_states'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + resource. Replaces any existing policy. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + 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 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a resource. + Returns an empty policy if the resource exists and does + not have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + 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_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns permissions that a caller has on the specified resource. + If the resource does not exist, this will return an empty set of + permissions, not a NOT_FOUND error. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + 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 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def send_command_to_device(self) -> Callable[ + [device_manager.SendCommandToDeviceRequest], + device_manager.SendCommandToDeviceResponse]: + r"""Return a callable for the send command to device method over gRPC. + + Sends a command to the specified device. In order for a device + to be able to receive commands, it must: + + 1) be connected to Cloud IoT Core using the MQTT protocol, and + 2) be subscribed to the group of MQTT topics specified by + /devices/{device-id}/commands/#. This subscription will + receive commands at the top-level topic + /devices/{device-id}/commands as well as commands for + subfolders, like /devices/{device-id}/commands/subfolder. + Note that subscribing to specific subfolders is not + supported. If the command could not be delivered to the + device, this method will return an error; in particular, if + the device is not subscribed, this method will return + FAILED_PRECONDITION. Otherwise, this method will return OK. + If the subscription is QoS 1, at least once delivery will be + guaranteed; for QoS 0, no acknowledgment will be expected + from the device. + + Returns: + Callable[[~.SendCommandToDeviceRequest], + ~.SendCommandToDeviceResponse]: + 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 'send_command_to_device' not in self._stubs: + self._stubs['send_command_to_device'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/SendCommandToDevice', + request_serializer=device_manager.SendCommandToDeviceRequest.serialize, + response_deserializer=device_manager.SendCommandToDeviceResponse.deserialize, + ) + return self._stubs['send_command_to_device'] + + @property + def bind_device_to_gateway(self) -> Callable[ + [device_manager.BindDeviceToGatewayRequest], + device_manager.BindDeviceToGatewayResponse]: + r"""Return a callable for the bind device to gateway method over gRPC. + + Associates the device with the gateway. + + Returns: + Callable[[~.BindDeviceToGatewayRequest], + ~.BindDeviceToGatewayResponse]: + 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 'bind_device_to_gateway' not in self._stubs: + self._stubs['bind_device_to_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/BindDeviceToGateway', + request_serializer=device_manager.BindDeviceToGatewayRequest.serialize, + response_deserializer=device_manager.BindDeviceToGatewayResponse.deserialize, + ) + return self._stubs['bind_device_to_gateway'] + + @property + def unbind_device_from_gateway(self) -> Callable[ + [device_manager.UnbindDeviceFromGatewayRequest], + device_manager.UnbindDeviceFromGatewayResponse]: + r"""Return a callable for the unbind device from gateway method over gRPC. + + Deletes the association between the device and the + gateway. + + Returns: + Callable[[~.UnbindDeviceFromGatewayRequest], + ~.UnbindDeviceFromGatewayResponse]: + 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 'unbind_device_from_gateway' not in self._stubs: + self._stubs['unbind_device_from_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/UnbindDeviceFromGateway', + request_serializer=device_manager.UnbindDeviceFromGatewayRequest.serialize, + response_deserializer=device_manager.UnbindDeviceFromGatewayResponse.deserialize, + ) + return self._stubs['unbind_device_from_gateway'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DeviceManagerGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc_asyncio.py new file mode 100644 index 00000000..167d9a7c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc_asyncio.py @@ -0,0 +1,762 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DeviceManagerTransport, DEFAULT_CLIENT_INFO +from .grpc import DeviceManagerGrpcTransport + + +class DeviceManagerGrpcAsyncIOTransport(DeviceManagerTransport): + """gRPC AsyncIO backend transport for DeviceManager. + + Internet of Things (IoT) service. Securely connect and manage + IoT devices. + + 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 = 'cloudiot.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudiot.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_device_registry(self) -> Callable[ + [device_manager.CreateDeviceRegistryRequest], + Awaitable[resources.DeviceRegistry]]: + r"""Return a callable for the create device registry method over gRPC. + + Creates a device registry that contains devices. + + Returns: + Callable[[~.CreateDeviceRegistryRequest], + Awaitable[~.DeviceRegistry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_device_registry' not in self._stubs: + self._stubs['create_device_registry'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/CreateDeviceRegistry', + request_serializer=device_manager.CreateDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs['create_device_registry'] + + @property + def get_device_registry(self) -> Callable[ + [device_manager.GetDeviceRegistryRequest], + Awaitable[resources.DeviceRegistry]]: + r"""Return a callable for the get device registry method over gRPC. + + Gets a device registry configuration. + + Returns: + Callable[[~.GetDeviceRegistryRequest], + Awaitable[~.DeviceRegistry]]: + 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_device_registry' not in self._stubs: + self._stubs['get_device_registry'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/GetDeviceRegistry', + request_serializer=device_manager.GetDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs['get_device_registry'] + + @property + def update_device_registry(self) -> Callable[ + [device_manager.UpdateDeviceRegistryRequest], + Awaitable[resources.DeviceRegistry]]: + r"""Return a callable for the update device registry method over gRPC. + + Updates a device registry configuration. + + Returns: + Callable[[~.UpdateDeviceRegistryRequest], + Awaitable[~.DeviceRegistry]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_device_registry' not in self._stubs: + self._stubs['update_device_registry'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/UpdateDeviceRegistry', + request_serializer=device_manager.UpdateDeviceRegistryRequest.serialize, + response_deserializer=resources.DeviceRegistry.deserialize, + ) + return self._stubs['update_device_registry'] + + @property + def delete_device_registry(self) -> Callable[ + [device_manager.DeleteDeviceRegistryRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete device registry method over gRPC. + + Deletes a device registry configuration. + + Returns: + Callable[[~.DeleteDeviceRegistryRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_device_registry' not in self._stubs: + self._stubs['delete_device_registry'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/DeleteDeviceRegistry', + request_serializer=device_manager.DeleteDeviceRegistryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_device_registry'] + + @property + def list_device_registries(self) -> Callable[ + [device_manager.ListDeviceRegistriesRequest], + Awaitable[device_manager.ListDeviceRegistriesResponse]]: + r"""Return a callable for the list device registries method over gRPC. + + Lists device registries. + + Returns: + Callable[[~.ListDeviceRegistriesRequest], + Awaitable[~.ListDeviceRegistriesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_device_registries' not in self._stubs: + self._stubs['list_device_registries'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/ListDeviceRegistries', + request_serializer=device_manager.ListDeviceRegistriesRequest.serialize, + response_deserializer=device_manager.ListDeviceRegistriesResponse.deserialize, + ) + return self._stubs['list_device_registries'] + + @property + def create_device(self) -> Callable[ + [device_manager.CreateDeviceRequest], + Awaitable[resources.Device]]: + r"""Return a callable for the create device method over gRPC. + + Creates a device in a device registry. + + Returns: + Callable[[~.CreateDeviceRequest], + Awaitable[~.Device]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_device' not in self._stubs: + self._stubs['create_device'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/CreateDevice', + request_serializer=device_manager.CreateDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs['create_device'] + + @property + def get_device(self) -> Callable[ + [device_manager.GetDeviceRequest], + Awaitable[resources.Device]]: + r"""Return a callable for the get device method over gRPC. + + Gets details about a device. + + Returns: + Callable[[~.GetDeviceRequest], + Awaitable[~.Device]]: + 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_device' not in self._stubs: + self._stubs['get_device'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/GetDevice', + request_serializer=device_manager.GetDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs['get_device'] + + @property + def update_device(self) -> Callable[ + [device_manager.UpdateDeviceRequest], + Awaitable[resources.Device]]: + r"""Return a callable for the update device method over gRPC. + + Updates a device. + + Returns: + Callable[[~.UpdateDeviceRequest], + Awaitable[~.Device]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_device' not in self._stubs: + self._stubs['update_device'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/UpdateDevice', + request_serializer=device_manager.UpdateDeviceRequest.serialize, + response_deserializer=resources.Device.deserialize, + ) + return self._stubs['update_device'] + + @property + def delete_device(self) -> Callable[ + [device_manager.DeleteDeviceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete device method over gRPC. + + Deletes a device. + + Returns: + Callable[[~.DeleteDeviceRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_device' not in self._stubs: + self._stubs['delete_device'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/DeleteDevice', + request_serializer=device_manager.DeleteDeviceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_device'] + + @property + def list_devices(self) -> Callable[ + [device_manager.ListDevicesRequest], + Awaitable[device_manager.ListDevicesResponse]]: + r"""Return a callable for the list devices method over gRPC. + + List devices in a device registry. + + Returns: + Callable[[~.ListDevicesRequest], + Awaitable[~.ListDevicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_devices' not in self._stubs: + self._stubs['list_devices'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/ListDevices', + request_serializer=device_manager.ListDevicesRequest.serialize, + response_deserializer=device_manager.ListDevicesResponse.deserialize, + ) + return self._stubs['list_devices'] + + @property + def modify_cloud_to_device_config(self) -> Callable[ + [device_manager.ModifyCloudToDeviceConfigRequest], + Awaitable[resources.DeviceConfig]]: + r"""Return a callable for the modify cloud to device config method over gRPC. + + Modifies the configuration for the device, which is + eventually sent from the Cloud IoT Core servers. Returns + the modified configuration version and its metadata. + + Returns: + Callable[[~.ModifyCloudToDeviceConfigRequest], + Awaitable[~.DeviceConfig]]: + 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 'modify_cloud_to_device_config' not in self._stubs: + self._stubs['modify_cloud_to_device_config'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/ModifyCloudToDeviceConfig', + request_serializer=device_manager.ModifyCloudToDeviceConfigRequest.serialize, + response_deserializer=resources.DeviceConfig.deserialize, + ) + return self._stubs['modify_cloud_to_device_config'] + + @property + def list_device_config_versions(self) -> Callable[ + [device_manager.ListDeviceConfigVersionsRequest], + Awaitable[device_manager.ListDeviceConfigVersionsResponse]]: + r"""Return a callable for the list device config versions method over gRPC. + + Lists the last few versions of the device + configuration in descending order (i.e.: newest first). + + Returns: + Callable[[~.ListDeviceConfigVersionsRequest], + Awaitable[~.ListDeviceConfigVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_device_config_versions' not in self._stubs: + self._stubs['list_device_config_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/ListDeviceConfigVersions', + request_serializer=device_manager.ListDeviceConfigVersionsRequest.serialize, + response_deserializer=device_manager.ListDeviceConfigVersionsResponse.deserialize, + ) + return self._stubs['list_device_config_versions'] + + @property + def list_device_states(self) -> Callable[ + [device_manager.ListDeviceStatesRequest], + Awaitable[device_manager.ListDeviceStatesResponse]]: + r"""Return a callable for the list device states method over gRPC. + + Lists the last few versions of the device state in + descending order (i.e.: newest first). + + Returns: + Callable[[~.ListDeviceStatesRequest], + Awaitable[~.ListDeviceStatesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_device_states' not in self._stubs: + self._stubs['list_device_states'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/ListDeviceStates', + request_serializer=device_manager.ListDeviceStatesRequest.serialize, + response_deserializer=device_manager.ListDeviceStatesResponse.deserialize, + ) + return self._stubs['list_device_states'] + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + resource. Replaces any existing policy. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + 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 'set_iam_policy' not in self._stubs: + self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_iam_policy'] + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy for a resource. + Returns an empty policy if the resource exists and does + not have a policy set. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + 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_iam_policy' not in self._stubs: + self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns permissions that a caller has on the specified resource. + If the resource does not exist, this will return an empty set of + permissions, not a NOT_FOUND error. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + 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 'test_iam_permissions' not in self._stubs: + self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def send_command_to_device(self) -> Callable[ + [device_manager.SendCommandToDeviceRequest], + Awaitable[device_manager.SendCommandToDeviceResponse]]: + r"""Return a callable for the send command to device method over gRPC. + + Sends a command to the specified device. In order for a device + to be able to receive commands, it must: + + 1) be connected to Cloud IoT Core using the MQTT protocol, and + 2) be subscribed to the group of MQTT topics specified by + /devices/{device-id}/commands/#. This subscription will + receive commands at the top-level topic + /devices/{device-id}/commands as well as commands for + subfolders, like /devices/{device-id}/commands/subfolder. + Note that subscribing to specific subfolders is not + supported. If the command could not be delivered to the + device, this method will return an error; in particular, if + the device is not subscribed, this method will return + FAILED_PRECONDITION. Otherwise, this method will return OK. + If the subscription is QoS 1, at least once delivery will be + guaranteed; for QoS 0, no acknowledgment will be expected + from the device. + + Returns: + Callable[[~.SendCommandToDeviceRequest], + Awaitable[~.SendCommandToDeviceResponse]]: + 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 'send_command_to_device' not in self._stubs: + self._stubs['send_command_to_device'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/SendCommandToDevice', + request_serializer=device_manager.SendCommandToDeviceRequest.serialize, + response_deserializer=device_manager.SendCommandToDeviceResponse.deserialize, + ) + return self._stubs['send_command_to_device'] + + @property + def bind_device_to_gateway(self) -> Callable[ + [device_manager.BindDeviceToGatewayRequest], + Awaitable[device_manager.BindDeviceToGatewayResponse]]: + r"""Return a callable for the bind device to gateway method over gRPC. + + Associates the device with the gateway. + + Returns: + Callable[[~.BindDeviceToGatewayRequest], + Awaitable[~.BindDeviceToGatewayResponse]]: + 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 'bind_device_to_gateway' not in self._stubs: + self._stubs['bind_device_to_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/BindDeviceToGateway', + request_serializer=device_manager.BindDeviceToGatewayRequest.serialize, + response_deserializer=device_manager.BindDeviceToGatewayResponse.deserialize, + ) + return self._stubs['bind_device_to_gateway'] + + @property + def unbind_device_from_gateway(self) -> Callable[ + [device_manager.UnbindDeviceFromGatewayRequest], + Awaitable[device_manager.UnbindDeviceFromGatewayResponse]]: + r"""Return a callable for the unbind device from gateway method over gRPC. + + Deletes the association between the device and the + gateway. + + Returns: + Callable[[~.UnbindDeviceFromGatewayRequest], + Awaitable[~.UnbindDeviceFromGatewayResponse]]: + 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 'unbind_device_from_gateway' not in self._stubs: + self._stubs['unbind_device_from_gateway'] = self.grpc_channel.unary_unary( + '/google.cloud.iot.v1.DeviceManager/UnbindDeviceFromGateway', + request_serializer=device_manager.UnbindDeviceFromGatewayRequest.serialize, + response_deserializer=device_manager.UnbindDeviceFromGatewayResponse.deserialize, + ) + return self._stubs['unbind_device_from_gateway'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'DeviceManagerGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/rest.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/rest.py new file mode 100644 index 00000000..ab82fca3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/rest.py @@ -0,0 +1,2535 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from .base import DeviceManagerTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class DeviceManagerRestInterceptor: + """Interceptor for DeviceManager. + + 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 DeviceManagerRestTransport. + + .. code-block:: python + class MyCustomDeviceManagerInterceptor(DeviceManagerRestInterceptor): + def pre_bind_device_to_gateway(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_bind_device_to_gateway(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_device(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_device(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_device_registry(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_device_registry(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_device(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_device_registry(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_device(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_device(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_device_registry(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_device_registry(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_device_config_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_device_config_versions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_device_registries(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_device_registries(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_devices(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_devices(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_device_states(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_device_states(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_modify_cloud_to_device_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_modify_cloud_to_device_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_send_command_to_device(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_send_command_to_device(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_unbind_device_from_gateway(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_unbind_device_from_gateway(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_device(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_device(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_device_registry(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_device_registry(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DeviceManagerRestTransport(interceptor=MyCustomDeviceManagerInterceptor()) + client = DeviceManagerClient(transport=transport) + + + """ + def pre_bind_device_to_gateway(self, request: device_manager.BindDeviceToGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.BindDeviceToGatewayRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for bind_device_to_gateway + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_bind_device_to_gateway(self, response: device_manager.BindDeviceToGatewayResponse) -> device_manager.BindDeviceToGatewayResponse: + """Post-rpc interceptor for bind_device_to_gateway + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_create_device(self, request: device_manager.CreateDeviceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.CreateDeviceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_device + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_create_device(self, response: resources.Device) -> resources.Device: + """Post-rpc interceptor for create_device + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_create_device_registry(self, request: device_manager.CreateDeviceRegistryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.CreateDeviceRegistryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_device_registry + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_create_device_registry(self, response: resources.DeviceRegistry) -> resources.DeviceRegistry: + """Post-rpc interceptor for create_device_registry + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_delete_device(self, request: device_manager.DeleteDeviceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.DeleteDeviceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_device + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def pre_delete_device_registry(self, request: device_manager.DeleteDeviceRegistryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.DeleteDeviceRegistryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_device_registry + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def pre_get_device(self, request: device_manager.GetDeviceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.GetDeviceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_device + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_get_device(self, response: resources.Device) -> resources.Device: + """Post-rpc interceptor for get_device + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_get_device_registry(self, request: device_manager.GetDeviceRegistryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.GetDeviceRegistryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_device_registry + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_get_device_registry(self, response: resources.DeviceRegistry) -> resources.DeviceRegistry: + """Post-rpc interceptor for get_device_registry + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy(self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_list_device_config_versions(self, request: device_manager.ListDeviceConfigVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.ListDeviceConfigVersionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_device_config_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_list_device_config_versions(self, response: device_manager.ListDeviceConfigVersionsResponse) -> device_manager.ListDeviceConfigVersionsResponse: + """Post-rpc interceptor for list_device_config_versions + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_list_device_registries(self, request: device_manager.ListDeviceRegistriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.ListDeviceRegistriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_device_registries + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_list_device_registries(self, response: device_manager.ListDeviceRegistriesResponse) -> device_manager.ListDeviceRegistriesResponse: + """Post-rpc interceptor for list_device_registries + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_list_devices(self, request: device_manager.ListDevicesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.ListDevicesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_devices + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_list_devices(self, response: device_manager.ListDevicesResponse) -> device_manager.ListDevicesResponse: + """Post-rpc interceptor for list_devices + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_list_device_states(self, request: device_manager.ListDeviceStatesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.ListDeviceStatesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_device_states + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_list_device_states(self, response: device_manager.ListDeviceStatesResponse) -> device_manager.ListDeviceStatesResponse: + """Post-rpc interceptor for list_device_states + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_modify_cloud_to_device_config(self, request: device_manager.ModifyCloudToDeviceConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.ModifyCloudToDeviceConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for modify_cloud_to_device_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_modify_cloud_to_device_config(self, response: resources.DeviceConfig) -> resources.DeviceConfig: + """Post-rpc interceptor for modify_cloud_to_device_config + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_send_command_to_device(self, request: device_manager.SendCommandToDeviceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.SendCommandToDeviceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for send_command_to_device + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_send_command_to_device(self, response: device_manager.SendCommandToDeviceResponse) -> device_manager.SendCommandToDeviceResponse: + """Post-rpc interceptor for send_command_to_device + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy(self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions(self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_test_iam_permissions(self, response: iam_policy_pb2.TestIamPermissionsResponse) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_unbind_device_from_gateway(self, request: device_manager.UnbindDeviceFromGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.UnbindDeviceFromGatewayRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for unbind_device_from_gateway + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_unbind_device_from_gateway(self, response: device_manager.UnbindDeviceFromGatewayResponse) -> device_manager.UnbindDeviceFromGatewayResponse: + """Post-rpc interceptor for unbind_device_from_gateway + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_update_device(self, request: device_manager.UpdateDeviceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.UpdateDeviceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_device + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_update_device(self, response: resources.Device) -> resources.Device: + """Post-rpc interceptor for update_device + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + def pre_update_device_registry(self, request: device_manager.UpdateDeviceRegistryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.UpdateDeviceRegistryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_device_registry + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeviceManager server. + """ + return request, metadata + + def post_update_device_registry(self, response: resources.DeviceRegistry) -> resources.DeviceRegistry: + """Post-rpc interceptor for update_device_registry + + Override in a subclass to manipulate the response + after it is returned by the DeviceManager server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DeviceManagerRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DeviceManagerRestInterceptor + + +class DeviceManagerRestTransport(DeviceManagerTransport): + """REST backend transport for DeviceManager. + + Internet of Things (IoT) service. Securely connect and manage + IoT devices. + + 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 = 'cloudiot.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[DeviceManagerRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DeviceManagerRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BindDeviceToGateway(DeviceManagerRestStub): + def __hash__(self): + return hash("BindDeviceToGateway") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.BindDeviceToGatewayRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> device_manager.BindDeviceToGatewayResponse: + r"""Call the bind device to gateway method over HTTP. + + Args: + request (~.device_manager.BindDeviceToGatewayRequest): + The request object. Request for ``BindDeviceToGateway``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.BindDeviceToGatewayResponse: + Response for ``BindDeviceToGateway``. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/registries/*}:bindDeviceToGateway', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/registries/*/groups/*}:bindDeviceToGateway', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_bind_device_to_gateway(request, metadata) + pb_request = device_manager.BindDeviceToGatewayRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = device_manager.BindDeviceToGatewayResponse() + pb_resp = device_manager.BindDeviceToGatewayResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_bind_device_to_gateway(resp) + return resp + + class _CreateDevice(DeviceManagerRestStub): + def __hash__(self): + return hash("CreateDevice") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.CreateDeviceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Device: + r"""Call the create device method over HTTP. + + Args: + request (~.device_manager.CreateDeviceRequest): + The request object. Request for ``CreateDevice``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Device: + The device resource. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/registries/*}/devices', + 'body': 'device', + }, + ] + request, metadata = self._interceptor.pre_create_device(request, metadata) + pb_request = device_manager.CreateDeviceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Device() + pb_resp = resources.Device.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_device(resp) + return resp + + class _CreateDeviceRegistry(DeviceManagerRestStub): + def __hash__(self): + return hash("CreateDeviceRegistry") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.CreateDeviceRegistryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DeviceRegistry: + r"""Call the create device registry method over HTTP. + + Args: + request (~.device_manager.CreateDeviceRegistryRequest): + The request object. Request for ``CreateDeviceRegistry``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceRegistry: + A container for a group of devices. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/registries', + 'body': 'device_registry', + }, + ] + request, metadata = self._interceptor.pre_create_device_registry(request, metadata) + pb_request = device_manager.CreateDeviceRegistryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.DeviceRegistry() + pb_resp = resources.DeviceRegistry.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_device_registry(resp) + return resp + + class _DeleteDevice(DeviceManagerRestStub): + def __hash__(self): + return hash("DeleteDevice") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.DeleteDeviceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete device method over HTTP. + + Args: + request (~.device_manager.DeleteDeviceRequest): + The request object. Request for ``DeleteDevice``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_device(request, metadata) + pb_request = device_manager.DeleteDeviceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteDeviceRegistry(DeviceManagerRestStub): + def __hash__(self): + return hash("DeleteDeviceRegistry") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.DeleteDeviceRegistryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete device registry method over HTTP. + + Args: + request (~.device_manager.DeleteDeviceRegistryRequest): + The request object. Request for ``DeleteDeviceRegistry``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/registries/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_device_registry(request, metadata) + pb_request = device_manager.DeleteDeviceRegistryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetDevice(DeviceManagerRestStub): + def __hash__(self): + return hash("GetDevice") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.GetDeviceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Device: + r"""Call the get device method over HTTP. + + Args: + request (~.device_manager.GetDeviceRequest): + The request object. Request for ``GetDevice``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Device: + The device resource. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}', + }, + ] + request, metadata = self._interceptor.pre_get_device(request, metadata) + pb_request = device_manager.GetDeviceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resources.Device() + pb_resp = resources.Device.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_device(resp) + return resp + + class _GetDeviceRegistry(DeviceManagerRestStub): + def __hash__(self): + return hash("GetDeviceRegistry") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.GetDeviceRegistryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DeviceRegistry: + r"""Call the get device registry method over HTTP. + + Args: + request (~.device_manager.GetDeviceRegistryRequest): + The request object. Request for ``GetDeviceRegistry``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceRegistry: + A container for a group of devices. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/registries/*}', + }, + ] + request, metadata = self._interceptor.pre_get_device_registry(request, metadata) + pb_request = device_manager.GetDeviceRegistryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resources.DeviceRegistry() + pb_resp = resources.DeviceRegistry.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_device_registry(resp) + return resp + + class _GetIamPolicy(DeviceManagerRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (~.iam_policy_pb2.GetIamPolicyRequest): + The request object. Request message for ``GetIamPolicy`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/registries/*}:getIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/registries/*/groups/*}:getIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _ListDeviceConfigVersions(DeviceManagerRestStub): + def __hash__(self): + return hash("ListDeviceConfigVersions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.ListDeviceConfigVersionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> device_manager.ListDeviceConfigVersionsResponse: + r"""Call the list device config + versions method over HTTP. + + Args: + request (~.device_manager.ListDeviceConfigVersionsRequest): + The request object. Request for ``ListDeviceConfigVersions``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.ListDeviceConfigVersionsResponse: + Response for ``ListDeviceConfigVersions``. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}/configVersions', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}/configVersions', + }, + ] + request, metadata = self._interceptor.pre_list_device_config_versions(request, metadata) + pb_request = device_manager.ListDeviceConfigVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = device_manager.ListDeviceConfigVersionsResponse() + pb_resp = device_manager.ListDeviceConfigVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_device_config_versions(resp) + return resp + + class _ListDeviceRegistries(DeviceManagerRestStub): + def __hash__(self): + return hash("ListDeviceRegistries") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.ListDeviceRegistriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> device_manager.ListDeviceRegistriesResponse: + r"""Call the list device registries method over HTTP. + + Args: + request (~.device_manager.ListDeviceRegistriesRequest): + The request object. Request for ``ListDeviceRegistries``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.ListDeviceRegistriesResponse: + Response for ``ListDeviceRegistries``. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/registries', + }, + ] + request, metadata = self._interceptor.pre_list_device_registries(request, metadata) + pb_request = device_manager.ListDeviceRegistriesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = device_manager.ListDeviceRegistriesResponse() + pb_resp = device_manager.ListDeviceRegistriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_device_registries(resp) + return resp + + class _ListDevices(DeviceManagerRestStub): + def __hash__(self): + return hash("ListDevices") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.ListDevicesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> device_manager.ListDevicesResponse: + r"""Call the list devices method over HTTP. + + Args: + request (~.device_manager.ListDevicesRequest): + The request object. Request for ``ListDevices``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.ListDevicesResponse: + Response for ``ListDevices``. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/registries/*}/devices', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/registries/*/groups/*}/devices', + }, + ] + request, metadata = self._interceptor.pre_list_devices(request, metadata) + pb_request = device_manager.ListDevicesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = device_manager.ListDevicesResponse() + pb_resp = device_manager.ListDevicesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_devices(resp) + return resp + + class _ListDeviceStates(DeviceManagerRestStub): + def __hash__(self): + return hash("ListDeviceStates") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.ListDeviceStatesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> device_manager.ListDeviceStatesResponse: + r"""Call the list device states method over HTTP. + + Args: + request (~.device_manager.ListDeviceStatesRequest): + The request object. Request for ``ListDeviceStates``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.ListDeviceStatesResponse: + Response for ``ListDeviceStates``. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}/states', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}/states', + }, + ] + request, metadata = self._interceptor.pre_list_device_states(request, metadata) + pb_request = device_manager.ListDeviceStatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = device_manager.ListDeviceStatesResponse() + pb_resp = device_manager.ListDeviceStatesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_device_states(resp) + return resp + + class _ModifyCloudToDeviceConfig(DeviceManagerRestStub): + def __hash__(self): + return hash("ModifyCloudToDeviceConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.ModifyCloudToDeviceConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DeviceConfig: + r"""Call the modify cloud to device + config method over HTTP. + + Args: + request (~.device_manager.ModifyCloudToDeviceConfigRequest): + The request object. Request for ``ModifyCloudToDeviceConfig``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceConfig: + The device configuration. Eventually + delivered to devices. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}:modifyCloudToDeviceConfig', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}:modifyCloudToDeviceConfig', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_modify_cloud_to_device_config(request, metadata) + pb_request = device_manager.ModifyCloudToDeviceConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.DeviceConfig() + pb_resp = resources.DeviceConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_modify_cloud_to_device_config(resp) + return resp + + class _SendCommandToDevice(DeviceManagerRestStub): + def __hash__(self): + return hash("SendCommandToDevice") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.SendCommandToDeviceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> device_manager.SendCommandToDeviceResponse: + r"""Call the send command to device method over HTTP. + + Args: + request (~.device_manager.SendCommandToDeviceRequest): + The request object. Request for ``SendCommandToDevice``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.SendCommandToDeviceResponse: + Response for ``SendCommandToDevice``. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}:sendCommandToDevice', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}:sendCommandToDevice', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_send_command_to_device(request, metadata) + pb_request = device_manager.SendCommandToDeviceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = device_manager.SendCommandToDeviceResponse() + pb_resp = device_manager.SendCommandToDeviceResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_send_command_to_device(resp) + return resp + + class _SetIamPolicy(DeviceManagerRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (~.iam_policy_pb2.SetIamPolicyRequest): + The request object. Request message for ``SetIamPolicy`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/registries/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/registries/*/groups/*}:setIamPolicy', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(DeviceManagerRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (~.iam_policy_pb2.TestIamPermissionsRequest): + The request object. Request message for ``TestIamPermissions`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/registries/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/registries/*/groups/*}:testIamPermissions', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UnbindDeviceFromGateway(DeviceManagerRestStub): + def __hash__(self): + return hash("UnbindDeviceFromGateway") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.UnbindDeviceFromGatewayRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> device_manager.UnbindDeviceFromGatewayResponse: + r"""Call the unbind device from + gateway method over HTTP. + + Args: + request (~.device_manager.UnbindDeviceFromGatewayRequest): + The request object. Request for ``UnbindDeviceFromGateway``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.device_manager.UnbindDeviceFromGatewayResponse: + Response for ``UnbindDeviceFromGateway``. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/registries/*}:unbindDeviceFromGateway', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/registries/*/groups/*}:unbindDeviceFromGateway', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_unbind_device_from_gateway(request, metadata) + pb_request = device_manager.UnbindDeviceFromGatewayRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = device_manager.UnbindDeviceFromGatewayResponse() + pb_resp = device_manager.UnbindDeviceFromGatewayResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_unbind_device_from_gateway(resp) + return resp + + class _UpdateDevice(DeviceManagerRestStub): + def __hash__(self): + return hash("UpdateDevice") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.UpdateDeviceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Device: + r"""Call the update device method over HTTP. + + Args: + request (~.device_manager.UpdateDeviceRequest): + The request object. Request for ``UpdateDevice``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Device: + The device resource. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{device.name=projects/*/locations/*/registries/*/devices/*}', + 'body': 'device', + }, +{ + 'method': 'patch', + 'uri': '/v1/{device.name=projects/*/locations/*/registries/*/groups/*/devices/*}', + 'body': 'device', + }, + ] + request, metadata = self._interceptor.pre_update_device(request, metadata) + pb_request = device_manager.UpdateDeviceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Device() + pb_resp = resources.Device.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_device(resp) + return resp + + class _UpdateDeviceRegistry(DeviceManagerRestStub): + def __hash__(self): + return hash("UpdateDeviceRegistry") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: device_manager.UpdateDeviceRegistryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DeviceRegistry: + r"""Call the update device registry method over HTTP. + + Args: + request (~.device_manager.UpdateDeviceRegistryRequest): + The request object. Request for ``UpdateDeviceRegistry``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DeviceRegistry: + A container for a group of devices. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{device_registry.name=projects/*/locations/*/registries/*}', + 'body': 'device_registry', + }, + ] + request, metadata = self._interceptor.pre_update_device_registry(request, metadata) + pb_request = device_manager.UpdateDeviceRegistryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.DeviceRegistry() + pb_resp = resources.DeviceRegistry.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_device_registry(resp) + return resp + + @property + def bind_device_to_gateway(self) -> Callable[ + [device_manager.BindDeviceToGatewayRequest], + device_manager.BindDeviceToGatewayResponse]: + # 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._BindDeviceToGateway(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_device(self) -> Callable[ + [device_manager.CreateDeviceRequest], + resources.Device]: + # 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._CreateDevice(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_device_registry(self) -> Callable[ + [device_manager.CreateDeviceRegistryRequest], + resources.DeviceRegistry]: + # 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._CreateDeviceRegistry(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_device(self) -> Callable[ + [device_manager.DeleteDeviceRequest], + empty_pb2.Empty]: + # 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._DeleteDevice(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_device_registry(self) -> Callable[ + [device_manager.DeleteDeviceRegistryRequest], + empty_pb2.Empty]: + # 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._DeleteDeviceRegistry(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_device(self) -> Callable[ + [device_manager.GetDeviceRequest], + resources.Device]: + # 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._GetDevice(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_device_registry(self) -> Callable[ + [device_manager.GetDeviceRegistryRequest], + resources.DeviceRegistry]: + # 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._GetDeviceRegistry(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + policy_pb2.Policy]: + # 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._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_device_config_versions(self) -> Callable[ + [device_manager.ListDeviceConfigVersionsRequest], + device_manager.ListDeviceConfigVersionsResponse]: + # 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._ListDeviceConfigVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_device_registries(self) -> Callable[ + [device_manager.ListDeviceRegistriesRequest], + device_manager.ListDeviceRegistriesResponse]: + # 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._ListDeviceRegistries(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_devices(self) -> Callable[ + [device_manager.ListDevicesRequest], + device_manager.ListDevicesResponse]: + # 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._ListDevices(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_device_states(self) -> Callable[ + [device_manager.ListDeviceStatesRequest], + device_manager.ListDeviceStatesResponse]: + # 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._ListDeviceStates(self._session, self._host, self._interceptor) # type: ignore + + @property + def modify_cloud_to_device_config(self) -> Callable[ + [device_manager.ModifyCloudToDeviceConfigRequest], + resources.DeviceConfig]: + # 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._ModifyCloudToDeviceConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def send_command_to_device(self) -> Callable[ + [device_manager.SendCommandToDeviceRequest], + device_manager.SendCommandToDeviceResponse]: + # 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._SendCommandToDevice(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy(self) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + policy_pb2.Policy]: + # 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._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse]: + # 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._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def unbind_device_from_gateway(self) -> Callable[ + [device_manager.UnbindDeviceFromGatewayRequest], + device_manager.UnbindDeviceFromGatewayResponse]: + # 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._UnbindDeviceFromGateway(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_device(self) -> Callable[ + [device_manager.UpdateDeviceRequest], + resources.Device]: + # 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._UpdateDevice(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_device_registry(self) -> Callable[ + [device_manager.UpdateDeviceRegistryRequest], + resources.DeviceRegistry]: + # 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._UpdateDeviceRegistry(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'DeviceManagerRestTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/iot_v1/types/__init__.py new file mode 100644 index 00000000..3457476c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/types/__init__.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .device_manager import ( + BindDeviceToGatewayRequest, + BindDeviceToGatewayResponse, + CreateDeviceRegistryRequest, + CreateDeviceRequest, + DeleteDeviceRegistryRequest, + DeleteDeviceRequest, + GatewayListOptions, + GetDeviceRegistryRequest, + GetDeviceRequest, + ListDeviceConfigVersionsRequest, + ListDeviceConfigVersionsResponse, + ListDeviceRegistriesRequest, + ListDeviceRegistriesResponse, + ListDevicesRequest, + ListDevicesResponse, + ListDeviceStatesRequest, + ListDeviceStatesResponse, + ModifyCloudToDeviceConfigRequest, + SendCommandToDeviceRequest, + SendCommandToDeviceResponse, + UnbindDeviceFromGatewayRequest, + UnbindDeviceFromGatewayResponse, + UpdateDeviceRegistryRequest, + UpdateDeviceRequest, +) +from .resources import ( + Device, + DeviceConfig, + DeviceCredential, + DeviceRegistry, + DeviceState, + EventNotificationConfig, + GatewayConfig, + HttpConfig, + MqttConfig, + PublicKeyCertificate, + PublicKeyCredential, + RegistryCredential, + StateNotificationConfig, + X509CertificateDetails, + GatewayAuthMethod, + GatewayType, + HttpState, + LogLevel, + MqttState, + PublicKeyCertificateFormat, + PublicKeyFormat, +) + +__all__ = ( + 'BindDeviceToGatewayRequest', + 'BindDeviceToGatewayResponse', + 'CreateDeviceRegistryRequest', + 'CreateDeviceRequest', + 'DeleteDeviceRegistryRequest', + 'DeleteDeviceRequest', + 'GatewayListOptions', + 'GetDeviceRegistryRequest', + 'GetDeviceRequest', + 'ListDeviceConfigVersionsRequest', + 'ListDeviceConfigVersionsResponse', + 'ListDeviceRegistriesRequest', + 'ListDeviceRegistriesResponse', + 'ListDevicesRequest', + 'ListDevicesResponse', + 'ListDeviceStatesRequest', + 'ListDeviceStatesResponse', + 'ModifyCloudToDeviceConfigRequest', + 'SendCommandToDeviceRequest', + 'SendCommandToDeviceResponse', + 'UnbindDeviceFromGatewayRequest', + 'UnbindDeviceFromGatewayResponse', + 'UpdateDeviceRegistryRequest', + 'UpdateDeviceRequest', + 'Device', + 'DeviceConfig', + 'DeviceCredential', + 'DeviceRegistry', + 'DeviceState', + 'EventNotificationConfig', + 'GatewayConfig', + 'HttpConfig', + 'MqttConfig', + 'PublicKeyCertificate', + 'PublicKeyCredential', + 'RegistryCredential', + 'StateNotificationConfig', + 'X509CertificateDetails', + 'GatewayAuthMethod', + 'GatewayType', + 'HttpState', + 'LogLevel', + 'MqttState', + 'PublicKeyCertificateFormat', + 'PublicKeyFormat', +) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/types/device_manager.py b/owl-bot-staging/v1/google/cloud/iot_v1/types/device_manager.py new file mode 100644 index 00000000..699eabc4 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/types/device_manager.py @@ -0,0 +1,688 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.cloud.iot_v1.types import resources +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.iot.v1', + manifest={ + 'CreateDeviceRegistryRequest', + 'GetDeviceRegistryRequest', + 'DeleteDeviceRegistryRequest', + 'UpdateDeviceRegistryRequest', + 'ListDeviceRegistriesRequest', + 'ListDeviceRegistriesResponse', + 'CreateDeviceRequest', + 'GetDeviceRequest', + 'UpdateDeviceRequest', + 'DeleteDeviceRequest', + 'ListDevicesRequest', + 'GatewayListOptions', + 'ListDevicesResponse', + 'ModifyCloudToDeviceConfigRequest', + 'ListDeviceConfigVersionsRequest', + 'ListDeviceConfigVersionsResponse', + 'ListDeviceStatesRequest', + 'ListDeviceStatesResponse', + 'SendCommandToDeviceRequest', + 'SendCommandToDeviceResponse', + 'BindDeviceToGatewayRequest', + 'BindDeviceToGatewayResponse', + 'UnbindDeviceFromGatewayRequest', + 'UnbindDeviceFromGatewayResponse', + }, +) + + +class CreateDeviceRegistryRequest(proto.Message): + r"""Request for ``CreateDeviceRegistry``. + + Attributes: + parent (str): + Required. The project and cloud region where this device + registry must be created. For example, + ``projects/example-project/locations/us-central1``. + device_registry (google.cloud.iot_v1.types.DeviceRegistry): + Required. The device registry. The field ``name`` must be + empty. The server will generate that field from the device + registry ``id`` provided and the ``parent`` field. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + device_registry: resources.DeviceRegistry = proto.Field( + proto.MESSAGE, + number=2, + message=resources.DeviceRegistry, + ) + + +class GetDeviceRegistryRequest(proto.Message): + r"""Request for ``GetDeviceRegistry``. + + Attributes: + name (str): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteDeviceRegistryRequest(proto.Message): + r"""Request for ``DeleteDeviceRegistry``. + + Attributes: + name (str): + Required. The name of the device registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDeviceRegistryRequest(proto.Message): + r"""Request for ``UpdateDeviceRegistry``. + + Attributes: + device_registry (google.cloud.iot_v1.types.DeviceRegistry): + Required. The new values for the device registry. The ``id`` + field must be empty, and the ``name`` field must indicate + the path of the resource. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Only updates the ``device_registry`` fields + indicated by this mask. The field mask must not be empty, + and it must not contain fields that are immutable or only + set by the server. Mutable top-level fields: + ``event_notification_config``, ``http_config``, + ``mqtt_config``, and ``state_notification_config``. + """ + + device_registry: resources.DeviceRegistry = proto.Field( + proto.MESSAGE, + number=1, + message=resources.DeviceRegistry, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListDeviceRegistriesRequest(proto.Message): + r"""Request for ``ListDeviceRegistries``. + + Attributes: + parent (str): + Required. The project and cloud region path. For example, + ``projects/example-project/locations/us-central1``. + page_size (int): + The maximum number of registries to return in the response. + If this value is zero, the service will select a default + size. A call may return fewer objects than requested. A + non-empty ``next_page_token`` in the response indicates that + more data is available. + page_token (str): + The value returned by the last + ``ListDeviceRegistriesResponse``; indicates that this is a + continuation of a prior ``ListDeviceRegistries`` call and + the system should return the next page of data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDeviceRegistriesResponse(proto.Message): + r"""Response for ``ListDeviceRegistries``. + + Attributes: + device_registries (MutableSequence[google.cloud.iot_v1.types.DeviceRegistry]): + The registries that matched the query. + next_page_token (str): + If not empty, indicates that there may be more registries + that match the request; this value should be passed in a new + ``ListDeviceRegistriesRequest``. + """ + + @property + def raw_page(self): + return self + + device_registries: MutableSequence[resources.DeviceRegistry] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.DeviceRegistry, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDeviceRequest(proto.Message): + r"""Request for ``CreateDevice``. + + Attributes: + parent (str): + Required. The name of the device registry where this device + should be created. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + device (google.cloud.iot_v1.types.Device): + Required. The device registration details. The field + ``name`` must be empty. The server generates ``name`` from + the device registry ``id`` and the ``parent`` field. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + device: resources.Device = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Device, + ) + + +class GetDeviceRequest(proto.Message): + r"""Request for ``GetDevice``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields of the ``Device`` resource to be returned in the + response. If the field mask is unset or empty, all fields + are returned. Fields have to be provided in snake_case + format, for example: ``last_heartbeat_time``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateDeviceRequest(proto.Message): + r"""Request for ``UpdateDevice``. + + Attributes: + device (google.cloud.iot_v1.types.Device): + Required. The new values for the device. The ``id`` and + ``num_id`` fields must be empty, and the field ``name`` must + specify the name path. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\ or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Only updates the ``device`` fields indicated by + this mask. The field mask must not be empty, and it must not + contain fields that are immutable or only set by the server. + Mutable top-level fields: ``credentials``, ``blocked``, and + ``metadata`` + """ + + device: resources.Device = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Device, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteDeviceRequest(proto.Message): + r"""Request for ``DeleteDevice``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDevicesRequest(proto.Message): + r"""Request for ``ListDevices``. + + Attributes: + parent (str): + Required. The device registry path. Required. For example, + ``projects/my-project/locations/us-central1/registries/my-registry``. + device_num_ids (MutableSequence[int]): + A list of device numeric IDs. If empty, this + field is ignored. Maximum IDs: 10,000. + device_ids (MutableSequence[str]): + A list of device string IDs. For example, + ``['device0', 'device12']``. If empty, this field is + ignored. Maximum IDs: 10,000 + field_mask (google.protobuf.field_mask_pb2.FieldMask): + The fields of the ``Device`` resource to be returned in the + response. The fields ``id`` and ``num_id`` are always + returned, along with any other fields specified in + snake_case format, for example: ``last_heartbeat_time``. + gateway_list_options (google.cloud.iot_v1.types.GatewayListOptions): + Options related to gateways. + page_size (int): + The maximum number of devices to return in the response. If + this value is zero, the service will select a default size. + A call may return fewer objects than requested. A non-empty + ``next_page_token`` in the response indicates that more data + is available. + page_token (str): + The value returned by the last ``ListDevicesResponse``; + indicates that this is a continuation of a prior + ``ListDevices`` call and the system should return the next + page of data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + device_num_ids: MutableSequence[int] = proto.RepeatedField( + proto.UINT64, + number=2, + ) + device_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=4, + message=field_mask_pb2.FieldMask, + ) + gateway_list_options: 'GatewayListOptions' = proto.Field( + proto.MESSAGE, + number=6, + message='GatewayListOptions', + ) + page_size: int = proto.Field( + proto.INT32, + number=100, + ) + page_token: str = proto.Field( + proto.STRING, + number=101, + ) + + +class GatewayListOptions(proto.Message): + r"""Options for limiting the list based on gateway type and + associations. + + 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: + gateway_type (google.cloud.iot_v1.types.GatewayType): + If ``GATEWAY`` is specified, only gateways are returned. If + ``NON_GATEWAY`` is specified, only non-gateway devices are + returned. If ``GATEWAY_TYPE_UNSPECIFIED`` is specified, all + devices are returned. + + This field is a member of `oneof`_ ``filter``. + associations_gateway_id (str): + If set, only devices associated with the specified gateway + are returned. The gateway ID can be numeric (``num_id``) or + the user-defined string (``id``). For example, if ``123`` is + specified, only devices bound to the gateway with ``num_id`` + 123 are returned. + + This field is a member of `oneof`_ ``filter``. + associations_device_id (str): + If set, returns only the gateways with which the specified + device is associated. The device ID can be numeric + (``num_id``) or the user-defined string (``id``). For + example, if ``456`` is specified, returns only the gateways + to which the device with ``num_id`` 456 is bound. + + This field is a member of `oneof`_ ``filter``. + """ + + gateway_type: resources.GatewayType = proto.Field( + proto.ENUM, + number=1, + oneof='filter', + enum=resources.GatewayType, + ) + associations_gateway_id: str = proto.Field( + proto.STRING, + number=2, + oneof='filter', + ) + associations_device_id: str = proto.Field( + proto.STRING, + number=3, + oneof='filter', + ) + + +class ListDevicesResponse(proto.Message): + r"""Response for ``ListDevices``. + + Attributes: + devices (MutableSequence[google.cloud.iot_v1.types.Device]): + The devices that match the request. + next_page_token (str): + If not empty, indicates that there may be more devices that + match the request; this value should be passed in a new + ``ListDevicesRequest``. + """ + + @property + def raw_page(self): + return self + + devices: MutableSequence[resources.Device] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Device, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ModifyCloudToDeviceConfigRequest(proto.Message): + r"""Request for ``ModifyCloudToDeviceConfig``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + version_to_update (int): + The version number to update. If this value + is zero, it will not check the version number of + the server and will always update the current + version; otherwise, this update will fail if the + version number found on the server does not + match this version number. This is used to + support multiple simultaneous updates without + losing data. + binary_data (bytes): + Required. The configuration data for the + device. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + version_to_update: int = proto.Field( + proto.INT64, + number=2, + ) + binary_data: bytes = proto.Field( + proto.BYTES, + number=3, + ) + + +class ListDeviceConfigVersionsRequest(proto.Message): + r"""Request for ``ListDeviceConfigVersions``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + num_versions (int): + The number of versions to list. Versions are + listed in decreasing order of the version + number. The maximum number of versions retained + is 10. If this value is zero, it will return all + the versions available. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + num_versions: int = proto.Field( + proto.INT32, + number=2, + ) + + +class ListDeviceConfigVersionsResponse(proto.Message): + r"""Response for ``ListDeviceConfigVersions``. + + Attributes: + device_configs (MutableSequence[google.cloud.iot_v1.types.DeviceConfig]): + The device configuration for the last few + versions. Versions are listed in decreasing + order, starting from the most recent one. + """ + + device_configs: MutableSequence[resources.DeviceConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.DeviceConfig, + ) + + +class ListDeviceStatesRequest(proto.Message): + r"""Request for ``ListDeviceStates``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + num_states (int): + The number of states to list. States are + listed in descending order of update time. The + maximum number of states retained is 10. If this + value is zero, it will return all the states + available. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + num_states: int = proto.Field( + proto.INT32, + number=2, + ) + + +class ListDeviceStatesResponse(proto.Message): + r"""Response for ``ListDeviceStates``. + + Attributes: + device_states (MutableSequence[google.cloud.iot_v1.types.DeviceState]): + The last few device states. States are listed + in descending order of server update time, + starting from the most recent one. + """ + + device_states: MutableSequence[resources.DeviceState] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.DeviceState, + ) + + +class SendCommandToDeviceRequest(proto.Message): + r"""Request for ``SendCommandToDevice``. + + Attributes: + name (str): + Required. The name of the device. For example, + ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` + or + ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. + binary_data (bytes): + Required. The command data to send to the + device. + subfolder (str): + Optional subfolder for the command. If empty, + the command will be delivered to the + /devices/{device-id}/commands topic, otherwise + it will be delivered to the + /devices/{device-id}/commands/{subfolder} topic. + Multi-level subfolders are allowed. This field + must not have more than 256 characters, and must + not contain any MQTT wildcards ("+" or "#") or + null characters. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + binary_data: bytes = proto.Field( + proto.BYTES, + number=2, + ) + subfolder: str = proto.Field( + proto.STRING, + number=3, + ) + + +class SendCommandToDeviceResponse(proto.Message): + r"""Response for ``SendCommandToDevice``. + """ + + +class BindDeviceToGatewayRequest(proto.Message): + r"""Request for ``BindDeviceToGateway``. + + Attributes: + parent (str): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + gateway_id (str): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + device_id (str): + Required. The device to associate with the specified + gateway. The value of ``device_id`` can be either the device + numeric ID or the user-defined device identifier. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + gateway_id: str = proto.Field( + proto.STRING, + number=2, + ) + device_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class BindDeviceToGatewayResponse(proto.Message): + r"""Response for ``BindDeviceToGateway``. + """ + + +class UnbindDeviceFromGatewayRequest(proto.Message): + r"""Request for ``UnbindDeviceFromGateway``. + + Attributes: + parent (str): + Required. The name of the registry. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + gateway_id (str): + Required. The value of ``gateway_id`` can be either the + device numeric ID or the user-defined device identifier. + device_id (str): + Required. The device to disassociate from the specified + gateway. The value of ``device_id`` can be either the device + numeric ID or the user-defined device identifier. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + gateway_id: str = proto.Field( + proto.STRING, + number=2, + ) + device_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UnbindDeviceFromGatewayResponse(proto.Message): + r"""Response for ``UnbindDeviceFromGateway``. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/types/resources.py b/owl-bot-staging/v1/google/cloud/iot_v1/types/resources.py new file mode 100644 index 00000000..2fb358c5 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/iot_v1/types/resources.py @@ -0,0 +1,868 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License 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.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.iot.v1', + manifest={ + 'MqttState', + 'HttpState', + 'LogLevel', + 'GatewayType', + 'GatewayAuthMethod', + 'PublicKeyCertificateFormat', + 'PublicKeyFormat', + 'Device', + 'GatewayConfig', + 'DeviceRegistry', + 'MqttConfig', + 'HttpConfig', + 'EventNotificationConfig', + 'StateNotificationConfig', + 'RegistryCredential', + 'X509CertificateDetails', + 'PublicKeyCertificate', + 'DeviceCredential', + 'PublicKeyCredential', + 'DeviceConfig', + 'DeviceState', + }, +) + + +class MqttState(proto.Enum): + r"""Indicates whether an MQTT connection is enabled or disabled. + See the field description for details. + + Values: + MQTT_STATE_UNSPECIFIED (0): + No MQTT state specified. If not specified, + MQTT will be enabled by default. + MQTT_ENABLED (1): + Enables a MQTT connection. + MQTT_DISABLED (2): + Disables a MQTT connection. + """ + MQTT_STATE_UNSPECIFIED = 0 + MQTT_ENABLED = 1 + MQTT_DISABLED = 2 + + +class HttpState(proto.Enum): + r"""Indicates whether DeviceService (HTTP) is enabled or disabled + for the registry. See the field description for details. + + Values: + HTTP_STATE_UNSPECIFIED (0): + No HTTP state specified. If not specified, + DeviceService will be enabled by default. + HTTP_ENABLED (1): + Enables DeviceService (HTTP) service for the + registry. + HTTP_DISABLED (2): + Disables DeviceService (HTTP) service for the + registry. + """ + HTTP_STATE_UNSPECIFIED = 0 + HTTP_ENABLED = 1 + HTTP_DISABLED = 2 + + +class LogLevel(proto.Enum): + r"""**Beta Feature** + + The logging verbosity for device activity. Specifies which events + should be written to logs. For example, if the LogLevel is ERROR, + only events that terminate in errors will be logged. LogLevel is + inclusive; enabling INFO logging will also enable ERROR logging. + + Values: + LOG_LEVEL_UNSPECIFIED (0): + No logging specified. If not specified, + logging will be disabled. + NONE (10): + Disables logging. + ERROR (20): + Error events will be logged. + INFO (30): + Informational events will be logged, such as + connections and disconnections. + DEBUG (40): + All events will be logged. + """ + LOG_LEVEL_UNSPECIFIED = 0 + NONE = 10 + ERROR = 20 + INFO = 30 + DEBUG = 40 + + +class GatewayType(proto.Enum): + r"""Gateway type. + + Values: + GATEWAY_TYPE_UNSPECIFIED (0): + If unspecified, the device is considered a + non-gateway device. + GATEWAY (1): + The device is a gateway. + NON_GATEWAY (2): + The device is not a gateway. + """ + GATEWAY_TYPE_UNSPECIFIED = 0 + GATEWAY = 1 + NON_GATEWAY = 2 + + +class GatewayAuthMethod(proto.Enum): + r"""The gateway authorization/authentication method. This setting + determines how Cloud IoT Core authorizes/authenticate devices to + access the gateway. + + Values: + GATEWAY_AUTH_METHOD_UNSPECIFIED (0): + No authentication/authorization method + specified. No devices are allowed to access the + gateway. + ASSOCIATION_ONLY (1): + The device is authenticated through the + gateway association only. Device credentials are + ignored even if provided. + DEVICE_AUTH_TOKEN_ONLY (2): + The device is authenticated through its own + credentials. Gateway association is not checked. + ASSOCIATION_AND_DEVICE_AUTH_TOKEN (3): + The device is authenticated through both + device credentials and gateway association. The + device must be bound to the gateway and must + provide its own credentials. + """ + GATEWAY_AUTH_METHOD_UNSPECIFIED = 0 + ASSOCIATION_ONLY = 1 + DEVICE_AUTH_TOKEN_ONLY = 2 + ASSOCIATION_AND_DEVICE_AUTH_TOKEN = 3 + + +class PublicKeyCertificateFormat(proto.Enum): + r"""The supported formats for the public key. + + Values: + UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT (0): + The format has not been specified. This is an + invalid default value and must not be used. + X509_CERTIFICATE_PEM (1): + An X.509v3 certificate + (`RFC5280 `__), + encoded in base64, and wrapped by + ``-----BEGIN CERTIFICATE-----`` and + ``-----END CERTIFICATE-----``. + """ + UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT = 0 + X509_CERTIFICATE_PEM = 1 + + +class PublicKeyFormat(proto.Enum): + r"""The supported formats for the public key. + + Values: + UNSPECIFIED_PUBLIC_KEY_FORMAT (0): + The format has not been specified. This is an + invalid default value and must not be used. + RSA_PEM (3): + An RSA public key encoded in base64, and wrapped by + ``-----BEGIN PUBLIC KEY-----`` and + ``-----END PUBLIC KEY-----``. This can be used to verify + ``RS256`` signatures in JWT tokens + (`RFC7518 `__). + RSA_X509_PEM (1): + As RSA_PEM, but wrapped in an X.509v3 certificate + (`RFC5280 `__), + encoded in base64, and wrapped by + ``-----BEGIN CERTIFICATE-----`` and + ``-----END CERTIFICATE-----``. + ES256_PEM (2): + Public key for the ECDSA algorithm using P-256 and SHA-256, + encoded in base64, and wrapped by + ``-----BEGIN PUBLIC KEY-----`` and + ``-----END PUBLIC KEY-----``. This can be used to verify JWT + tokens with the ``ES256`` algorithm + (`RFC7518 `__). This + curve is defined in `OpenSSL `__ + as the ``prime256v1`` curve. + ES256_X509_PEM (4): + As ES256_PEM, but wrapped in an X.509v3 certificate + (`RFC5280 `__), + encoded in base64, and wrapped by + ``-----BEGIN CERTIFICATE-----`` and + ``-----END CERTIFICATE-----``. + """ + UNSPECIFIED_PUBLIC_KEY_FORMAT = 0 + RSA_PEM = 3 + RSA_X509_PEM = 1 + ES256_PEM = 2 + ES256_X509_PEM = 4 + + +class Device(proto.Message): + r"""The device resource. + + Attributes: + id (str): + The user-defined device identifier. The + device ID must be unique within a device + registry. + name (str): + The resource path name. For example, + ``projects/p1/locations/us-central1/registries/registry0/devices/dev0`` + or + ``projects/p1/locations/us-central1/registries/registry0/devices/{num_id}``. + When ``name`` is populated as a response from the service, + it always ends in the device numeric ID. + num_id (int): + [Output only] A server-defined unique numeric ID for the + device. This is a more compact way to identify devices, and + it is globally unique. + credentials (MutableSequence[google.cloud.iot_v1.types.DeviceCredential]): + The credentials used to authenticate this device. To allow + credential rotation without interruption, multiple device + credentials can be bound to this device. No more than 3 + credentials can be bound to a single device at a time. When + new credentials are added to a device, they are verified + against the registry credentials. For details, see the + description of the ``DeviceRegistry.credentials`` field. + last_heartbeat_time (google.protobuf.timestamp_pb2.Timestamp): + [Output only] The last time an MQTT ``PINGREQ`` was + received. This field applies only to devices connecting + through MQTT. MQTT clients usually only send ``PINGREQ`` + messages if the connection is idle, and no other messages + have been sent. Timestamps are periodically collected and + written to storage; they may be stale by a few minutes. + last_event_time (google.protobuf.timestamp_pb2.Timestamp): + [Output only] The last time a telemetry event was received. + Timestamps are periodically collected and written to + storage; they may be stale by a few minutes. + last_state_time (google.protobuf.timestamp_pb2.Timestamp): + [Output only] The last time a state event was received. + Timestamps are periodically collected and written to + storage; they may be stale by a few minutes. + last_config_ack_time (google.protobuf.timestamp_pb2.Timestamp): + [Output only] The last time a cloud-to-device config version + acknowledgment was received from the device. This field is + only for configurations sent through MQTT. + last_config_send_time (google.protobuf.timestamp_pb2.Timestamp): + [Output only] The last time a cloud-to-device config version + was sent to the device. + blocked (bool): + If a device is blocked, connections or + requests from this device will fail. Can be used + to temporarily prevent the device from + connecting if, for example, the sensor is + generating bad data and needs maintenance. + last_error_time (google.protobuf.timestamp_pb2.Timestamp): + [Output only] The time the most recent error occurred, such + as a failure to publish to Cloud Pub/Sub. This field is the + timestamp of 'last_error_status'. + last_error_status (google.rpc.status_pb2.Status): + [Output only] The error message of the most recent error, + such as a failure to publish to Cloud Pub/Sub. + 'last_error_time' is the timestamp of this field. If no + errors have occurred, this field has an empty message and + the status code 0 == OK. Otherwise, this field is expected + to have a status code other than OK. + config (google.cloud.iot_v1.types.DeviceConfig): + The most recent device configuration, which is eventually + sent from Cloud IoT Core to the device. If not present on + creation, the configuration will be initialized with an + empty payload and version value of ``1``. To update this + field after creation, use the + ``DeviceManager.ModifyCloudToDeviceConfig`` method. + state (google.cloud.iot_v1.types.DeviceState): + [Output only] The state most recently received from the + device. If no state has been reported, this field is not + present. + log_level (google.cloud.iot_v1.types.LogLevel): + **Beta Feature** + + The logging verbosity for device activity. If unspecified, + DeviceRegistry.log_level will be used. + metadata (MutableMapping[str, str]): + The metadata key-value pairs assigned to the device. This + metadata is not interpreted or indexed by Cloud IoT Core. It + can be used to add contextual information for the device. + + Keys must conform to the regular expression + [a-zA-Z][a-zA-Z0-9-_.+~%]+ and be less than 128 bytes in + length. + + Values are free-form strings. Each value must be less than + or equal to 32 KB in size. + + The total size of all keys and values must be less than 256 + KB, and the maximum number of key-value pairs is 500. + gateway_config (google.cloud.iot_v1.types.GatewayConfig): + Gateway-related configuration and state. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + num_id: int = proto.Field( + proto.UINT64, + number=3, + ) + credentials: MutableSequence['DeviceCredential'] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='DeviceCredential', + ) + last_heartbeat_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + last_event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + last_state_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=20, + message=timestamp_pb2.Timestamp, + ) + last_config_ack_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=14, + message=timestamp_pb2.Timestamp, + ) + last_config_send_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=18, + message=timestamp_pb2.Timestamp, + ) + blocked: bool = proto.Field( + proto.BOOL, + number=19, + ) + last_error_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + last_error_status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=11, + message=status_pb2.Status, + ) + config: 'DeviceConfig' = proto.Field( + proto.MESSAGE, + number=13, + message='DeviceConfig', + ) + state: 'DeviceState' = proto.Field( + proto.MESSAGE, + number=16, + message='DeviceState', + ) + log_level: 'LogLevel' = proto.Field( + proto.ENUM, + number=21, + enum='LogLevel', + ) + metadata: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=17, + ) + gateway_config: 'GatewayConfig' = proto.Field( + proto.MESSAGE, + number=24, + message='GatewayConfig', + ) + + +class GatewayConfig(proto.Message): + r"""Gateway-related configuration and state. + + Attributes: + gateway_type (google.cloud.iot_v1.types.GatewayType): + Indicates whether the device is a gateway. + gateway_auth_method (google.cloud.iot_v1.types.GatewayAuthMethod): + Indicates how to authorize and/or + authenticate devices to access the gateway. + last_accessed_gateway_id (str): + [Output only] The ID of the gateway the device accessed most + recently. + last_accessed_gateway_time (google.protobuf.timestamp_pb2.Timestamp): + [Output only] The most recent time at which the device + accessed the gateway specified in ``last_accessed_gateway``. + """ + + gateway_type: 'GatewayType' = proto.Field( + proto.ENUM, + number=1, + enum='GatewayType', + ) + gateway_auth_method: 'GatewayAuthMethod' = proto.Field( + proto.ENUM, + number=2, + enum='GatewayAuthMethod', + ) + last_accessed_gateway_id: str = proto.Field( + proto.STRING, + number=3, + ) + last_accessed_gateway_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class DeviceRegistry(proto.Message): + r"""A container for a group of devices. + + Attributes: + id (str): + The identifier of this device registry. For example, + ``myRegistry``. + name (str): + The resource path name. For example, + ``projects/example-project/locations/us-central1/registries/my-registry``. + event_notification_configs (MutableSequence[google.cloud.iot_v1.types.EventNotificationConfig]): + The configuration for notification of + telemetry events received from the device. All + telemetry events that were successfully + published by the device and acknowledged by + Cloud IoT Core are guaranteed to be delivered to + Cloud Pub/Sub. If multiple configurations match + a message, only the first matching configuration + is used. If you try to publish a device + telemetry event using MQTT without specifying a + Cloud Pub/Sub topic for the device's registry, + the connection closes automatically. If you try + to do so using an HTTP connection, an error is + returned. Up to 10 configurations may be + provided. + state_notification_config (google.cloud.iot_v1.types.StateNotificationConfig): + The configuration for notification of new + states received from the device. State updates + are guaranteed to be stored in the state + history, but notifications to Cloud Pub/Sub are + not guaranteed. For example, if permissions are + misconfigured or the specified topic doesn't + exist, no notification will be published but the + state will still be stored in Cloud IoT Core. + mqtt_config (google.cloud.iot_v1.types.MqttConfig): + The MQTT configuration for this device + registry. + http_config (google.cloud.iot_v1.types.HttpConfig): + The DeviceService (HTTP) configuration for + this device registry. + log_level (google.cloud.iot_v1.types.LogLevel): + **Beta Feature** + + The default logging verbosity for activity from devices in + this registry. The verbosity level can be overridden by + Device.log_level. + credentials (MutableSequence[google.cloud.iot_v1.types.RegistryCredential]): + The credentials used to verify the device + credentials. No more than 10 credentials can be + bound to a single registry at a time. The + verification process occurs at the time of + device creation or update. If this field is + empty, no verification is performed. Otherwise, + the credentials of a newly created device or + added credentials of an updated device should be + signed with one of these registry credentials. + + Note, however, that existing devices will never + be affected by modifications to this list of + credentials: after a device has been + successfully created in a registry, it should be + able to connect even if its registry credentials + are revoked, deleted, or modified. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + event_notification_configs: MutableSequence['EventNotificationConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='EventNotificationConfig', + ) + state_notification_config: 'StateNotificationConfig' = proto.Field( + proto.MESSAGE, + number=7, + message='StateNotificationConfig', + ) + mqtt_config: 'MqttConfig' = proto.Field( + proto.MESSAGE, + number=4, + message='MqttConfig', + ) + http_config: 'HttpConfig' = proto.Field( + proto.MESSAGE, + number=9, + message='HttpConfig', + ) + log_level: 'LogLevel' = proto.Field( + proto.ENUM, + number=11, + enum='LogLevel', + ) + credentials: MutableSequence['RegistryCredential'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='RegistryCredential', + ) + + +class MqttConfig(proto.Message): + r"""The configuration of MQTT for a device registry. + + Attributes: + mqtt_enabled_state (google.cloud.iot_v1.types.MqttState): + If enabled, allows connections using the MQTT + protocol. Otherwise, MQTT connections to this + registry will fail. + """ + + mqtt_enabled_state: 'MqttState' = proto.Field( + proto.ENUM, + number=1, + enum='MqttState', + ) + + +class HttpConfig(proto.Message): + r"""The configuration of the HTTP bridge for a device registry. + + Attributes: + http_enabled_state (google.cloud.iot_v1.types.HttpState): + If enabled, allows devices to use + DeviceService via the HTTP protocol. Otherwise, + any requests to DeviceService will fail for this + registry. + """ + + http_enabled_state: 'HttpState' = proto.Field( + proto.ENUM, + number=1, + enum='HttpState', + ) + + +class EventNotificationConfig(proto.Message): + r"""The configuration for forwarding telemetry events. + + Attributes: + subfolder_matches (str): + If the subfolder name matches this string + exactly, this configuration will be used. The + string must not include the leading '/' + character. If empty, all strings are matched. + This field is used only for telemetry events; + subfolders are not supported for state changes. + pubsub_topic_name (str): + A Cloud Pub/Sub topic name. For example, + ``projects/myProject/topics/deviceEvents``. + """ + + subfolder_matches: str = proto.Field( + proto.STRING, + number=2, + ) + pubsub_topic_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class StateNotificationConfig(proto.Message): + r"""The configuration for notification of new states received + from the device. + + Attributes: + pubsub_topic_name (str): + A Cloud Pub/Sub topic name. For example, + ``projects/myProject/topics/deviceEvents``. + """ + + pubsub_topic_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RegistryCredential(proto.Message): + r"""A server-stored registry credential used to validate device + credentials. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + public_key_certificate (google.cloud.iot_v1.types.PublicKeyCertificate): + A public key certificate used to verify the + device credentials. + + This field is a member of `oneof`_ ``credential``. + """ + + public_key_certificate: 'PublicKeyCertificate' = proto.Field( + proto.MESSAGE, + number=1, + oneof='credential', + message='PublicKeyCertificate', + ) + + +class X509CertificateDetails(proto.Message): + r"""Details of an X.509 certificate. For informational purposes + only. + + Attributes: + issuer (str): + The entity that signed the certificate. + subject (str): + The entity the certificate and public key + belong to. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time the certificate becomes valid. + expiry_time (google.protobuf.timestamp_pb2.Timestamp): + The time the certificate becomes invalid. + signature_algorithm (str): + The algorithm used to sign the certificate. + public_key_type (str): + The type of public key in the certificate. + """ + + issuer: str = proto.Field( + proto.STRING, + number=1, + ) + subject: str = proto.Field( + proto.STRING, + number=2, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + expiry_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + signature_algorithm: str = proto.Field( + proto.STRING, + number=5, + ) + public_key_type: str = proto.Field( + proto.STRING, + number=6, + ) + + +class PublicKeyCertificate(proto.Message): + r"""A public key certificate format and data. + + Attributes: + format_ (google.cloud.iot_v1.types.PublicKeyCertificateFormat): + The certificate format. + certificate (str): + The certificate data. + x509_details (google.cloud.iot_v1.types.X509CertificateDetails): + [Output only] The certificate details. Used only for X.509 + certificates. + """ + + format_: 'PublicKeyCertificateFormat' = proto.Field( + proto.ENUM, + number=1, + enum='PublicKeyCertificateFormat', + ) + certificate: str = proto.Field( + proto.STRING, + number=2, + ) + x509_details: 'X509CertificateDetails' = proto.Field( + proto.MESSAGE, + number=3, + message='X509CertificateDetails', + ) + + +class DeviceCredential(proto.Message): + r"""A server-stored device credential used for authentication. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + public_key (google.cloud.iot_v1.types.PublicKeyCredential): + A public key used to verify the signature of + JSON Web Tokens (JWTs). When adding a new device + credential, either via device creation or via + modifications, this public key credential may be + required to be signed by one of the registry + level certificates. More specifically, if the + registry contains at least one certificate, any + new device credential must be signed by one of + the registry certificates. As a result, when the + registry contains certificates, only X.509 + certificates are accepted as device credentials. + However, if the registry does not contain a + certificate, self-signed certificates and public + keys will be accepted. New device credentials + must be different from every registry-level + certificate. + + This field is a member of `oneof`_ ``credential``. + expiration_time (google.protobuf.timestamp_pb2.Timestamp): + [Optional] The time at which this credential becomes + invalid. This credential will be ignored for new client + authentication requests after this timestamp; however, it + will not be automatically deleted. + """ + + public_key: 'PublicKeyCredential' = proto.Field( + proto.MESSAGE, + number=2, + oneof='credential', + message='PublicKeyCredential', + ) + expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class PublicKeyCredential(proto.Message): + r"""A public key format and data. + + Attributes: + format_ (google.cloud.iot_v1.types.PublicKeyFormat): + The format of the key. + key (str): + The key data. + """ + + format_: 'PublicKeyFormat' = proto.Field( + proto.ENUM, + number=1, + enum='PublicKeyFormat', + ) + key: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeviceConfig(proto.Message): + r"""The device configuration. Eventually delivered to devices. + + Attributes: + version (int): + [Output only] The version of this update. The version number + is assigned by the server, and is always greater than 0 + after device creation. The version must be 0 on the + ``CreateDevice`` request if a ``config`` is specified; the + response of ``CreateDevice`` will always have a value of 1. + cloud_update_time (google.protobuf.timestamp_pb2.Timestamp): + [Output only] The time at which this configuration version + was updated in Cloud IoT Core. This timestamp is set by the + server. + device_ack_time (google.protobuf.timestamp_pb2.Timestamp): + [Output only] The time at which Cloud IoT Core received the + acknowledgment from the device, indicating that the device + has received this configuration version. If this field is + not present, the device has not yet acknowledged that it + received this version. Note that when the config was sent to + the device, many config versions may have been available in + Cloud IoT Core while the device was disconnected, and on + connection, only the latest version is sent to the device. + Some versions may never be sent to the device, and therefore + are never acknowledged. This timestamp is set by Cloud IoT + Core. + binary_data (bytes): + The device configuration data. + """ + + version: int = proto.Field( + proto.INT64, + number=1, + ) + cloud_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + device_ack_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + binary_data: bytes = proto.Field( + proto.BYTES, + number=4, + ) + + +class DeviceState(proto.Message): + r"""The device state, as reported by the device. + + Attributes: + update_time (google.protobuf.timestamp_pb2.Timestamp): + [Output only] The time at which this state version was + updated in Cloud IoT Core. + binary_data (bytes): + The device state data. + """ + + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + binary_data: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 00000000..574c5aed --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 00000000..a0d4d4e7 --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/iot_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py new file mode 100644 index 00000000..61baf13d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 BindDeviceToGateway +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_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.cloud import iot_v1 + + +async def sample_bind_device_to_gateway(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.BindDeviceToGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Make the request + response = await client.bind_device_to_gateway(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py new file mode 100644 index 00000000..c48f1559 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 BindDeviceToGateway +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_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.cloud import iot_v1 + + +def sample_bind_device_to_gateway(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.BindDeviceToGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Make the request + response = client.bind_device_to_gateway(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_async.py new file mode 100644 index 00000000..3d1d2c3d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDevice +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_CreateDevice_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.cloud import iot_v1 + + +async def sample_create_device(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.CreateDeviceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_device(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_CreateDevice_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_async.py new file mode 100644 index 00000000..7dc503e3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDeviceRegistry +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_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.cloud import iot_v1 + + +async def sample_create_device_registry(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.CreateDeviceRegistryRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_device_registry(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_sync.py new file mode 100644 index 00000000..25d2f292 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDeviceRegistry +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_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.cloud import iot_v1 + + +def sample_create_device_registry(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.CreateDeviceRegistryRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_device_registry(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_sync.py new file mode 100644 index 00000000..9c35511c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDevice +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_CreateDevice_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.cloud import iot_v1 + + +def sample_create_device(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.CreateDeviceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_device(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_CreateDevice_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_async.py new file mode 100644 index 00000000..0e36097e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDevice +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_DeleteDevice_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.cloud import iot_v1 + + +async def sample_delete_device(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.DeleteDeviceRequest( + name="name_value", + ) + + # Make the request + await client.delete_device(request=request) + + +# [END cloudiot_v1_generated_DeviceManager_DeleteDevice_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_async.py new file mode 100644 index 00000000..2a8701dd --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDeviceRegistry +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_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.cloud import iot_v1 + + +async def sample_delete_device_registry(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.DeleteDeviceRegistryRequest( + name="name_value", + ) + + # Make the request + await client.delete_device_registry(request=request) + + +# [END cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_sync.py new file mode 100644 index 00000000..4f0de1a9 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDeviceRegistry +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_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.cloud import iot_v1 + + +def sample_delete_device_registry(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.DeleteDeviceRegistryRequest( + name="name_value", + ) + + # Make the request + client.delete_device_registry(request=request) + + +# [END cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_sync.py new file mode 100644 index 00000000..3aea32a9 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDevice +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_DeleteDevice_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.cloud import iot_v1 + + +def sample_delete_device(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.DeleteDeviceRequest( + name="name_value", + ) + + # Make the request + client.delete_device(request=request) + + +# [END cloudiot_v1_generated_DeviceManager_DeleteDevice_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_async.py new file mode 100644 index 00000000..019c5f2e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDevice +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_GetDevice_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.cloud import iot_v1 + + +async def sample_get_device(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.GetDeviceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_device(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_GetDevice_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_async.py new file mode 100644 index 00000000..6f257d39 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDeviceRegistry +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_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.cloud import iot_v1 + + +async def sample_get_device_registry(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.GetDeviceRegistryRequest( + name="name_value", + ) + + # Make the request + response = await client.get_device_registry(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_sync.py new file mode 100644 index 00000000..d0015643 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDeviceRegistry +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_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.cloud import iot_v1 + + +def sample_get_device_registry(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.GetDeviceRegistryRequest( + name="name_value", + ) + + # Make the request + response = client.get_device_registry(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_sync.py new file mode 100644 index 00000000..e1df87a1 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDevice +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_GetDevice_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.cloud import iot_v1 + + +def sample_get_device(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.GetDeviceRequest( + name="name_value", + ) + + # Make the request + response = client.get_device(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_GetDevice_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_async.py new file mode 100644 index 00000000..00eb8cf6 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 GetIamPolicy +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_GetIamPolicy_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.cloud import iot_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_GetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_sync.py new file mode 100644 index 00000000..28eff036 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 GetIamPolicy +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_GetIamPolicy_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.cloud import iot_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_GetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_async.py new file mode 100644 index 00000000..ea8b8999 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDeviceConfigVersions +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_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.cloud import iot_v1 + + +async def sample_list_device_config_versions(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceConfigVersionsRequest( + name="name_value", + ) + + # Make the request + response = await client.list_device_config_versions(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py new file mode 100644 index 00000000..76cdcbc4 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDeviceConfigVersions +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_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.cloud import iot_v1 + + +def sample_list_device_config_versions(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceConfigVersionsRequest( + name="name_value", + ) + + # Make the request + response = client.list_device_config_versions(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_async.py new file mode 100644 index 00000000..0ee9ae87 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ListDeviceRegistries +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_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.cloud import iot_v1 + + +async def sample_list_device_registries(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceRegistriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_device_registries(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_sync.py new file mode 100644 index 00000000..15262ce7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ListDeviceRegistries +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_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.cloud import iot_v1 + + +def sample_list_device_registries(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceRegistriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_device_registries(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_async.py new file mode 100644 index 00000000..b532dc5a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDeviceStates +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_ListDeviceStates_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.cloud import iot_v1 + + +async def sample_list_device_states(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceStatesRequest( + name="name_value", + ) + + # Make the request + response = await client.list_device_states(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_ListDeviceStates_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_sync.py new file mode 100644 index 00000000..09ec53f4 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDeviceStates +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_ListDeviceStates_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.cloud import iot_v1 + + +def sample_list_device_states(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.ListDeviceStatesRequest( + name="name_value", + ) + + # Make the request + response = client.list_device_states(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_ListDeviceStates_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_async.py new file mode 100644 index 00000000..d392007d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ListDevices +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_ListDevices_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.cloud import iot_v1 + + +async def sample_list_devices(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.ListDevicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_devices(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudiot_v1_generated_DeviceManager_ListDevices_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_sync.py new file mode 100644 index 00000000..16a6b209 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ListDevices +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_ListDevices_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.cloud import iot_v1 + + +def sample_list_devices(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.ListDevicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_devices(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudiot_v1_generated_DeviceManager_ListDevices_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py new file mode 100644 index 00000000..14703599 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ModifyCloudToDeviceConfig +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_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.cloud import iot_v1 + + +async def sample_modify_cloud_to_device_config(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.ModifyCloudToDeviceConfigRequest( + name="name_value", + binary_data=b'binary_data_blob', + ) + + # Make the request + response = await client.modify_cloud_to_device_config(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py new file mode 100644 index 00000000..bc4164eb --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ModifyCloudToDeviceConfig +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_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.cloud import iot_v1 + + +def sample_modify_cloud_to_device_config(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.ModifyCloudToDeviceConfigRequest( + name="name_value", + binary_data=b'binary_data_blob', + ) + + # Make the request + response = client.modify_cloud_to_device_config(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_async.py new file mode 100644 index 00000000..bd1c1014 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 SendCommandToDevice +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_SendCommandToDevice_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.cloud import iot_v1 + + +async def sample_send_command_to_device(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.SendCommandToDeviceRequest( + name="name_value", + binary_data=b'binary_data_blob', + ) + + # Make the request + response = await client.send_command_to_device(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_SendCommandToDevice_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_sync.py new file mode 100644 index 00000000..0d333f44 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 SendCommandToDevice +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_SendCommandToDevice_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.cloud import iot_v1 + + +def sample_send_command_to_device(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.SendCommandToDeviceRequest( + name="name_value", + binary_data=b'binary_data_blob', + ) + + # Make the request + response = client.send_command_to_device(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_SendCommandToDevice_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_async.py new file mode 100644 index 00000000..88ed3581 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 SetIamPolicy +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_SetIamPolicy_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.cloud import iot_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_SetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_sync.py new file mode 100644 index 00000000..7954d439 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 SetIamPolicy +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_SetIamPolicy_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.cloud import iot_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_SetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_async.py new file mode 100644 index 00000000..ba456fc8 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 TestIamPermissions +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_TestIamPermissions_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.cloud import iot_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_TestIamPermissions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py new file mode 100644 index 00000000..5b0f765d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 TestIamPermissions +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_TestIamPermissions_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.cloud import iot_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_TestIamPermissions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py new file mode 100644 index 00000000..f4036ade --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 UnbindDeviceFromGateway +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_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.cloud import iot_v1 + + +async def sample_unbind_device_from_gateway(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.UnbindDeviceFromGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Make the request + response = await client.unbind_device_from_gateway(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py new file mode 100644 index 00000000..62618682 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 UnbindDeviceFromGateway +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_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.cloud import iot_v1 + + +def sample_unbind_device_from_gateway(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.UnbindDeviceFromGatewayRequest( + parent="parent_value", + gateway_id="gateway_id_value", + device_id="device_id_value", + ) + + # Make the request + response = client.unbind_device_from_gateway(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_async.py new file mode 100644 index 00000000..fe4de0a3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDevice +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_UpdateDevice_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.cloud import iot_v1 + + +async def sample_update_device(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.UpdateDeviceRequest( + ) + + # Make the request + response = await client.update_device(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_UpdateDevice_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_async.py new file mode 100644 index 00000000..a021e1ee --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDeviceRegistry +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_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.cloud import iot_v1 + + +async def sample_update_device_registry(): + # Create a client + client = iot_v1.DeviceManagerAsyncClient() + + # Initialize request argument(s) + request = iot_v1.UpdateDeviceRegistryRequest( + ) + + # Make the request + response = await client.update_device_registry(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_sync.py new file mode 100644 index 00000000..5557e07c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDeviceRegistry +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_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.cloud import iot_v1 + + +def sample_update_device_registry(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.UpdateDeviceRegistryRequest( + ) + + # Make the request + response = client.update_device_registry(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_sync.py new file mode 100644 index 00000000..8ad6706f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDevice +# 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-cloud-iot + + +# [START cloudiot_v1_generated_DeviceManager_UpdateDevice_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.cloud import iot_v1 + + +def sample_update_device(): + # Create a client + client = iot_v1.DeviceManagerClient() + + # Initialize request argument(s) + request = iot_v1.UpdateDeviceRequest( + ) + + # Make the request + response = client.update_device(request=request) + + # Handle the response + print(response) + +# [END cloudiot_v1_generated_DeviceManager_UpdateDevice_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.iot.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.iot.v1.json new file mode 100644 index 00000000..017afae4 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.iot.v1.json @@ -0,0 +1,3158 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.iot.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-iot", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.bind_device_to_gateway", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.BindDeviceToGateway", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "BindDeviceToGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.BindDeviceToGatewayRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "gateway_id", + "type": "str" + }, + { + "name": "device_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.BindDeviceToGatewayResponse", + "shortName": "bind_device_to_gateway" + }, + "description": "Sample for BindDeviceToGateway", + "file": "cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.bind_device_to_gateway", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.BindDeviceToGateway", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "BindDeviceToGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.BindDeviceToGatewayRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "gateway_id", + "type": "str" + }, + { + "name": "device_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.BindDeviceToGatewayResponse", + "shortName": "bind_device_to_gateway" + }, + "description": "Sample for BindDeviceToGateway", + "file": "cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.create_device_registry", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.CreateDeviceRegistry", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "CreateDeviceRegistry" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.CreateDeviceRegistryRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "device_registry", + "type": "google.cloud.iot_v1.types.DeviceRegistry" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.DeviceRegistry", + "shortName": "create_device_registry" + }, + "description": "Sample for CreateDeviceRegistry", + "file": "cloudiot_v1_generated_device_manager_create_device_registry_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_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": "cloudiot_v1_generated_device_manager_create_device_registry_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.create_device_registry", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.CreateDeviceRegistry", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "CreateDeviceRegistry" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.CreateDeviceRegistryRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "device_registry", + "type": "google.cloud.iot_v1.types.DeviceRegistry" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.DeviceRegistry", + "shortName": "create_device_registry" + }, + "description": "Sample for CreateDeviceRegistry", + "file": "cloudiot_v1_generated_device_manager_create_device_registry_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_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": "cloudiot_v1_generated_device_manager_create_device_registry_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.create_device", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.CreateDevice", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "CreateDevice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.CreateDeviceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "device", + "type": "google.cloud.iot_v1.types.Device" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.Device", + "shortName": "create_device" + }, + "description": "Sample for CreateDevice", + "file": "cloudiot_v1_generated_device_manager_create_device_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_CreateDevice_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": "cloudiot_v1_generated_device_manager_create_device_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.create_device", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.CreateDevice", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "CreateDevice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.CreateDeviceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "device", + "type": "google.cloud.iot_v1.types.Device" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.Device", + "shortName": "create_device" + }, + "description": "Sample for CreateDevice", + "file": "cloudiot_v1_generated_device_manager_create_device_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_CreateDevice_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": "cloudiot_v1_generated_device_manager_create_device_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.delete_device_registry", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.DeleteDeviceRegistry", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "DeleteDeviceRegistry" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.DeleteDeviceRegistryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_device_registry" + }, + "description": "Sample for DeleteDeviceRegistry", + "file": "cloudiot_v1_generated_device_manager_delete_device_registry_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_delete_device_registry_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.delete_device_registry", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.DeleteDeviceRegistry", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "DeleteDeviceRegistry" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.DeleteDeviceRegistryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_device_registry" + }, + "description": "Sample for DeleteDeviceRegistry", + "file": "cloudiot_v1_generated_device_manager_delete_device_registry_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_delete_device_registry_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.delete_device", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.DeleteDevice", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "DeleteDevice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.DeleteDeviceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_device" + }, + "description": "Sample for DeleteDevice", + "file": "cloudiot_v1_generated_device_manager_delete_device_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_DeleteDevice_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_delete_device_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.delete_device", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.DeleteDevice", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "DeleteDevice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.DeleteDeviceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_device" + }, + "description": "Sample for DeleteDevice", + "file": "cloudiot_v1_generated_device_manager_delete_device_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_DeleteDevice_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_delete_device_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.get_device_registry", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.GetDeviceRegistry", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "GetDeviceRegistry" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.GetDeviceRegistryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.DeviceRegistry", + "shortName": "get_device_registry" + }, + "description": "Sample for GetDeviceRegistry", + "file": "cloudiot_v1_generated_device_manager_get_device_registry_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_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": "cloudiot_v1_generated_device_manager_get_device_registry_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.get_device_registry", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.GetDeviceRegistry", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "GetDeviceRegistry" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.GetDeviceRegistryRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.DeviceRegistry", + "shortName": "get_device_registry" + }, + "description": "Sample for GetDeviceRegistry", + "file": "cloudiot_v1_generated_device_manager_get_device_registry_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_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": "cloudiot_v1_generated_device_manager_get_device_registry_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.get_device", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.GetDevice", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "GetDevice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.GetDeviceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.Device", + "shortName": "get_device" + }, + "description": "Sample for GetDevice", + "file": "cloudiot_v1_generated_device_manager_get_device_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_GetDevice_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": "cloudiot_v1_generated_device_manager_get_device_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.get_device", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.GetDevice", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "GetDevice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.GetDeviceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.Device", + "shortName": "get_device" + }, + "description": "Sample for GetDevice", + "file": "cloudiot_v1_generated_device_manager_get_device_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_GetDevice_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": "cloudiot_v1_generated_device_manager_get_device_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.GetIamPolicy", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudiot_v1_generated_device_manager_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.get_iam_policy", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.GetIamPolicy", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "cloudiot_v1_generated_device_manager_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.list_device_config_versions", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceConfigVersions", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "ListDeviceConfigVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.ListDeviceConfigVersionsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.ListDeviceConfigVersionsResponse", + "shortName": "list_device_config_versions" + }, + "description": "Sample for ListDeviceConfigVersions", + "file": "cloudiot_v1_generated_device_manager_list_device_config_versions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_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": "cloudiot_v1_generated_device_manager_list_device_config_versions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.list_device_config_versions", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceConfigVersions", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "ListDeviceConfigVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.ListDeviceConfigVersionsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.ListDeviceConfigVersionsResponse", + "shortName": "list_device_config_versions" + }, + "description": "Sample for ListDeviceConfigVersions", + "file": "cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_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": "cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.list_device_registries", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceRegistries", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "ListDeviceRegistries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.ListDeviceRegistriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.services.device_manager.pagers.ListDeviceRegistriesAsyncPager", + "shortName": "list_device_registries" + }, + "description": "Sample for ListDeviceRegistries", + "file": "cloudiot_v1_generated_device_manager_list_device_registries_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_list_device_registries_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.list_device_registries", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceRegistries", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "ListDeviceRegistries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.ListDeviceRegistriesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.services.device_manager.pagers.ListDeviceRegistriesPager", + "shortName": "list_device_registries" + }, + "description": "Sample for ListDeviceRegistries", + "file": "cloudiot_v1_generated_device_manager_list_device_registries_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_list_device_registries_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.list_device_states", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceStates", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "ListDeviceStates" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.ListDeviceStatesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.ListDeviceStatesResponse", + "shortName": "list_device_states" + }, + "description": "Sample for ListDeviceStates", + "file": "cloudiot_v1_generated_device_manager_list_device_states_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceStates_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": "cloudiot_v1_generated_device_manager_list_device_states_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.list_device_states", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceStates", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "ListDeviceStates" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.ListDeviceStatesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.ListDeviceStatesResponse", + "shortName": "list_device_states" + }, + "description": "Sample for ListDeviceStates", + "file": "cloudiot_v1_generated_device_manager_list_device_states_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceStates_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": "cloudiot_v1_generated_device_manager_list_device_states_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.list_devices", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.ListDevices", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "ListDevices" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.ListDevicesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.services.device_manager.pagers.ListDevicesAsyncPager", + "shortName": "list_devices" + }, + "description": "Sample for ListDevices", + "file": "cloudiot_v1_generated_device_manager_list_devices_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_ListDevices_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_list_devices_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.list_devices", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.ListDevices", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "ListDevices" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.ListDevicesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.services.device_manager.pagers.ListDevicesPager", + "shortName": "list_devices" + }, + "description": "Sample for ListDevices", + "file": "cloudiot_v1_generated_device_manager_list_devices_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_ListDevices_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_list_devices_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.modify_cloud_to_device_config", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.ModifyCloudToDeviceConfig", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "ModifyCloudToDeviceConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.ModifyCloudToDeviceConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "binary_data", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.DeviceConfig", + "shortName": "modify_cloud_to_device_config" + }, + "description": "Sample for ModifyCloudToDeviceConfig", + "file": "cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.modify_cloud_to_device_config", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.ModifyCloudToDeviceConfig", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "ModifyCloudToDeviceConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.ModifyCloudToDeviceConfigRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "binary_data", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.DeviceConfig", + "shortName": "modify_cloud_to_device_config" + }, + "description": "Sample for ModifyCloudToDeviceConfig", + "file": "cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.send_command_to_device", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.SendCommandToDevice", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "SendCommandToDevice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.SendCommandToDeviceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "binary_data", + "type": "bytes" + }, + { + "name": "subfolder", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.SendCommandToDeviceResponse", + "shortName": "send_command_to_device" + }, + "description": "Sample for SendCommandToDevice", + "file": "cloudiot_v1_generated_device_manager_send_command_to_device_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_SendCommandToDevice_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_send_command_to_device_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.send_command_to_device", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.SendCommandToDevice", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "SendCommandToDevice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.SendCommandToDeviceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "binary_data", + "type": "bytes" + }, + { + "name": "subfolder", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.SendCommandToDeviceResponse", + "shortName": "send_command_to_device" + }, + "description": "Sample for SendCommandToDevice", + "file": "cloudiot_v1_generated_device_manager_send_command_to_device_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_SendCommandToDevice_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_send_command_to_device_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.SetIamPolicy", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudiot_v1_generated_device_manager_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.set_iam_policy", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.SetIamPolicy", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "cloudiot_v1_generated_device_manager_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.TestIamPermissions", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudiot_v1_generated_device_manager_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.TestIamPermissions", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.unbind_device_from_gateway", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.UnbindDeviceFromGateway", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "UnbindDeviceFromGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.UnbindDeviceFromGatewayRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "gateway_id", + "type": "str" + }, + { + "name": "device_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.UnbindDeviceFromGatewayResponse", + "shortName": "unbind_device_from_gateway" + }, + "description": "Sample for UnbindDeviceFromGateway", + "file": "cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.unbind_device_from_gateway", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.UnbindDeviceFromGateway", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "UnbindDeviceFromGateway" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.UnbindDeviceFromGatewayRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "gateway_id", + "type": "str" + }, + { + "name": "device_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.UnbindDeviceFromGatewayResponse", + "shortName": "unbind_device_from_gateway" + }, + "description": "Sample for UnbindDeviceFromGateway", + "file": "cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.update_device_registry", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.UpdateDeviceRegistry", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "UpdateDeviceRegistry" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.UpdateDeviceRegistryRequest" + }, + { + "name": "device_registry", + "type": "google.cloud.iot_v1.types.DeviceRegistry" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.DeviceRegistry", + "shortName": "update_device_registry" + }, + "description": "Sample for UpdateDeviceRegistry", + "file": "cloudiot_v1_generated_device_manager_update_device_registry_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_update_device_registry_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.update_device_registry", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.UpdateDeviceRegistry", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "UpdateDeviceRegistry" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.UpdateDeviceRegistryRequest" + }, + { + "name": "device_registry", + "type": "google.cloud.iot_v1.types.DeviceRegistry" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.DeviceRegistry", + "shortName": "update_device_registry" + }, + "description": "Sample for UpdateDeviceRegistry", + "file": "cloudiot_v1_generated_device_manager_update_device_registry_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_update_device_registry_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", + "shortName": "DeviceManagerAsyncClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.update_device", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.UpdateDevice", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "UpdateDevice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.UpdateDeviceRequest" + }, + { + "name": "device", + "type": "google.cloud.iot_v1.types.Device" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.Device", + "shortName": "update_device" + }, + "description": "Sample for UpdateDevice", + "file": "cloudiot_v1_generated_device_manager_update_device_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_UpdateDevice_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_update_device_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iot_v1.DeviceManagerClient", + "shortName": "DeviceManagerClient" + }, + "fullName": "google.cloud.iot_v1.DeviceManagerClient.update_device", + "method": { + "fullName": "google.cloud.iot.v1.DeviceManager.UpdateDevice", + "service": { + "fullName": "google.cloud.iot.v1.DeviceManager", + "shortName": "DeviceManager" + }, + "shortName": "UpdateDevice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iot_v1.types.UpdateDeviceRequest" + }, + { + "name": "device", + "type": "google.cloud.iot_v1.types.Device" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iot_v1.types.Device", + "shortName": "update_device" + }, + "description": "Sample for UpdateDevice", + "file": "cloudiot_v1_generated_device_manager_update_device_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudiot_v1_generated_DeviceManager_UpdateDevice_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudiot_v1_generated_device_manager_update_device_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1/scripts/fixup_iot_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_iot_v1_keywords.py new file mode 100644 index 00000000..f59d0544 --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_iot_v1_keywords.py @@ -0,0 +1,194 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class iotCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'bind_device_to_gateway': ('parent', 'gateway_id', 'device_id', ), + 'create_device': ('parent', 'device', ), + 'create_device_registry': ('parent', 'device_registry', ), + 'delete_device': ('name', ), + 'delete_device_registry': ('name', ), + 'get_device': ('name', 'field_mask', ), + 'get_device_registry': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'list_device_config_versions': ('name', 'num_versions', ), + 'list_device_registries': ('parent', 'page_size', 'page_token', ), + 'list_devices': ('parent', 'device_num_ids', 'device_ids', 'field_mask', 'gateway_list_options', 'page_size', 'page_token', ), + 'list_device_states': ('name', 'num_states', ), + 'modify_cloud_to_device_config': ('name', 'binary_data', 'version_to_update', ), + 'send_command_to_device': ('name', 'binary_data', 'subfolder', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'unbind_device_from_gateway': ('parent', 'gateway_id', 'device_id', ), + 'update_device': ('device', 'update_mask', ), + 'update_device_registry': ('device_registry', 'update_mask', ), + } + + 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=iotCallTransformer(), +): + """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 iot 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/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 00000000..d264052f --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-iot' + + +description = "Google Cloud Iot API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/iot/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +url = "https://github.com/googleapis/python-iot" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1/testing/constraints-3.10.txt b/owl-bot-staging/v1/testing/constraints-3.10.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.11.txt b/owl-bot-staging/v1/testing/constraints-3.11.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.12.txt b/owl-bot-staging/v1/testing/constraints-3.12.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt new file mode 100644 index 00000000..2beecf99 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/v1/testing/constraints-3.8.txt b/owl-bot-staging/v1/testing/constraints-3.8.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.9.txt b/owl-bot-staging/v1/testing/constraints-3.9.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/iot_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/iot_v1/__init__.py new file mode 100644 index 00000000..231bc125 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/iot_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/iot_v1/test_device_manager.py b/owl-bot-staging/v1/tests/unit/gapic/iot_v1/test_device_manager.py new file mode 100644 index 00000000..1bb501dd --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/iot_v1/test_device_manager.py @@ -0,0 +1,10954 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.iot_v1.services.device_manager import DeviceManagerAsyncClient +from google.cloud.iot_v1.services.device_manager import DeviceManagerClient +from google.cloud.iot_v1.services.device_manager import pagers +from google.cloud.iot_v1.services.device_manager import transports +from google.cloud.iot_v1.types import device_manager +from google.cloud.iot_v1.types import resources +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DeviceManagerClient._get_default_mtls_endpoint(None) is None + assert DeviceManagerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DeviceManagerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DeviceManagerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DeviceManagerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DeviceManagerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DeviceManagerClient, "grpc"), + (DeviceManagerAsyncClient, "grpc_asyncio"), + (DeviceManagerClient, "rest"), +]) +def test_device_manager_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 == ( + 'cloudiot.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudiot.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DeviceManagerGrpcTransport, "grpc"), + (transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DeviceManagerRestTransport, "rest"), +]) +def test_device_manager_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", [ + (DeviceManagerClient, "grpc"), + (DeviceManagerAsyncClient, "grpc_asyncio"), + (DeviceManagerClient, "rest"), +]) +def test_device_manager_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 == ( + 'cloudiot.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudiot.googleapis.com' + ) + + +def test_device_manager_client_get_transport_class(): + transport = DeviceManagerClient.get_transport_class() + available_transports = [ + transports.DeviceManagerGrpcTransport, + transports.DeviceManagerRestTransport, + ] + assert transport in available_transports + + transport = DeviceManagerClient.get_transport_class("grpc") + assert transport == transports.DeviceManagerGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc"), + (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio"), + (DeviceManagerClient, transports.DeviceManagerRestTransport, "rest"), +]) +@mock.patch.object(DeviceManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerClient)) +@mock.patch.object(DeviceManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerAsyncClient)) +def test_device_manager_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(DeviceManagerClient, '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(DeviceManagerClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc", "true"), + (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc", "false"), + (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DeviceManagerClient, transports.DeviceManagerRestTransport, "rest", "true"), + (DeviceManagerClient, transports.DeviceManagerRestTransport, "rest", "false"), +]) +@mock.patch.object(DeviceManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerClient)) +@mock.patch.object(DeviceManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_device_manager_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + DeviceManagerClient, DeviceManagerAsyncClient +]) +@mock.patch.object(DeviceManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerClient)) +@mock.patch.object(DeviceManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerAsyncClient)) +def test_device_manager_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc"), + (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio"), + (DeviceManagerClient, transports.DeviceManagerRestTransport, "rest"), +]) +def test_device_manager_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc", grpc_helpers), + (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DeviceManagerClient, transports.DeviceManagerRestTransport, "rest", None), +]) +def test_device_manager_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_device_manager_client_client_options_from_dict(): + with mock.patch('google.cloud.iot_v1.services.device_manager.transports.DeviceManagerGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DeviceManagerClient( + 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", [ + (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc", grpc_helpers), + (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_device_manager_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudiot.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudiot', +), + scopes=None, + default_host="cloudiot.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.CreateDeviceRegistryRequest, + dict, +]) +def test_create_device_registry(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry( + id='id_value', + name='name_value', + log_level=resources.LogLevel.NONE, + ) + response = client.create_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.CreateDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.log_level == resources.LogLevel.NONE + + +def test_create_device_registry_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device_registry), + '__call__') as call: + client.create_device_registry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.CreateDeviceRegistryRequest() + +@pytest.mark.asyncio +async def test_create_device_registry_async(transport: str = 'grpc_asyncio', request_type=device_manager.CreateDeviceRegistryRequest): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry( + id='id_value', + name='name_value', + log_level=resources.LogLevel.NONE, + )) + response = await client.create_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.CreateDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.log_level == resources.LogLevel.NONE + + +@pytest.mark.asyncio +async def test_create_device_registry_async_from_dict(): + await test_create_device_registry_async(request_type=dict) + + +def test_create_device_registry_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.CreateDeviceRegistryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device_registry), + '__call__') as call: + call.return_value = resources.DeviceRegistry() + client.create_device_registry(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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_device_registry_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.CreateDeviceRegistryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device_registry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) + await client.create_device_registry(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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_device_registry_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_device_registry( + parent='parent_value', + device_registry=resources.DeviceRegistry(id='id_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].device_registry + mock_val = resources.DeviceRegistry(id='id_value') + assert arg == mock_val + + +def test_create_device_registry_flattened_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_device_registry( + device_manager.CreateDeviceRegistryRequest(), + parent='parent_value', + device_registry=resources.DeviceRegistry(id='id_value'), + ) + +@pytest.mark.asyncio +async def test_create_device_registry_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_device_registry( + parent='parent_value', + device_registry=resources.DeviceRegistry(id='id_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].device_registry + mock_val = resources.DeviceRegistry(id='id_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_device_registry_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_device_registry( + device_manager.CreateDeviceRegistryRequest(), + parent='parent_value', + device_registry=resources.DeviceRegistry(id='id_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.GetDeviceRegistryRequest, + dict, +]) +def test_get_device_registry(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + 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_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry( + id='id_value', + name='name_value', + log_level=resources.LogLevel.NONE, + ) + response = client.get_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.GetDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.log_level == resources.LogLevel.NONE + + +def test_get_device_registry_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_device_registry), + '__call__') as call: + client.get_device_registry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.GetDeviceRegistryRequest() + +@pytest.mark.asyncio +async def test_get_device_registry_async(transport: str = 'grpc_asyncio', request_type=device_manager.GetDeviceRegistryRequest): + client = DeviceManagerAsyncClient( + 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_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry( + id='id_value', + name='name_value', + log_level=resources.LogLevel.NONE, + )) + response = await client.get_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.GetDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.log_level == resources.LogLevel.NONE + + +@pytest.mark.asyncio +async def test_get_device_registry_async_from_dict(): + await test_get_device_registry_async(request_type=dict) + + +def test_get_device_registry_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.GetDeviceRegistryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_device_registry), + '__call__') as call: + call.return_value = resources.DeviceRegistry() + client.get_device_registry(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_device_registry_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.GetDeviceRegistryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_device_registry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) + await client.get_device_registry(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_device_registry_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_device_registry( + 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_device_registry_flattened_error(): + client = DeviceManagerClient( + 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_device_registry( + device_manager.GetDeviceRegistryRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_device_registry_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_device_registry( + 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_device_registry_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_device_registry( + device_manager.GetDeviceRegistryRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.UpdateDeviceRegistryRequest, + dict, +]) +def test_update_device_registry(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry( + id='id_value', + name='name_value', + log_level=resources.LogLevel.NONE, + ) + response = client.update_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.UpdateDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.log_level == resources.LogLevel.NONE + + +def test_update_device_registry_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device_registry), + '__call__') as call: + client.update_device_registry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.UpdateDeviceRegistryRequest() + +@pytest.mark.asyncio +async def test_update_device_registry_async(transport: str = 'grpc_asyncio', request_type=device_manager.UpdateDeviceRegistryRequest): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry( + id='id_value', + name='name_value', + log_level=resources.LogLevel.NONE, + )) + response = await client.update_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.UpdateDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.log_level == resources.LogLevel.NONE + + +@pytest.mark.asyncio +async def test_update_device_registry_async_from_dict(): + await test_update_device_registry_async(request_type=dict) + + +def test_update_device_registry_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.UpdateDeviceRegistryRequest() + + request.device_registry.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device_registry), + '__call__') as call: + call.return_value = resources.DeviceRegistry() + client.update_device_registry(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', + 'device_registry.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_device_registry_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.UpdateDeviceRegistryRequest() + + request.device_registry.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device_registry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) + await client.update_device_registry(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', + 'device_registry.name=name_value', + ) in kw['metadata'] + + +def test_update_device_registry_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_device_registry( + device_registry=resources.DeviceRegistry(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].device_registry + mock_val = resources.DeviceRegistry(id='id_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_device_registry_flattened_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_device_registry( + device_manager.UpdateDeviceRegistryRequest(), + device_registry=resources.DeviceRegistry(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_device_registry_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceRegistry() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_device_registry( + device_registry=resources.DeviceRegistry(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].device_registry + mock_val = resources.DeviceRegistry(id='id_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_device_registry_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_device_registry( + device_manager.UpdateDeviceRegistryRequest(), + device_registry=resources.DeviceRegistry(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.DeleteDeviceRegistryRequest, + dict, +]) +def test_delete_device_registry(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + 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.delete_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.DeleteDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_device_registry_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_device_registry), + '__call__') as call: + client.delete_device_registry() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.DeleteDeviceRegistryRequest() + +@pytest.mark.asyncio +async def test_delete_device_registry_async(transport: str = 'grpc_asyncio', request_type=device_manager.DeleteDeviceRegistryRequest): + client = DeviceManagerAsyncClient( + 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.delete_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_device_registry(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.DeleteDeviceRegistryRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_device_registry_async_from_dict(): + await test_delete_device_registry_async(request_type=dict) + + +def test_delete_device_registry_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.DeleteDeviceRegistryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_device_registry), + '__call__') as call: + call.return_value = None + client.delete_device_registry(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_delete_device_registry_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.DeleteDeviceRegistryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_device_registry), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_device_registry(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_delete_device_registry_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_device_registry( + 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_delete_device_registry_flattened_error(): + client = DeviceManagerClient( + 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.delete_device_registry( + device_manager.DeleteDeviceRegistryRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_device_registry_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_device_registry), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_device_registry( + 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_delete_device_registry_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_device_registry( + device_manager.DeleteDeviceRegistryRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.ListDeviceRegistriesRequest, + dict, +]) +def test_list_device_registries(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_registries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceRegistriesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_device_registries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDeviceRegistriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeviceRegistriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_device_registries_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_registries), + '__call__') as call: + client.list_device_registries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDeviceRegistriesRequest() + +@pytest.mark.asyncio +async def test_list_device_registries_async(transport: str = 'grpc_asyncio', request_type=device_manager.ListDeviceRegistriesRequest): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_registries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceRegistriesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_device_registries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDeviceRegistriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeviceRegistriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_device_registries_async_from_dict(): + await test_list_device_registries_async(request_type=dict) + + +def test_list_device_registries_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.ListDeviceRegistriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_registries), + '__call__') as call: + call.return_value = device_manager.ListDeviceRegistriesResponse() + client.list_device_registries(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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_device_registries_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.ListDeviceRegistriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_registries), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceRegistriesResponse()) + await client.list_device_registries(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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_device_registries_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_registries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceRegistriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_device_registries( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_device_registries_flattened_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_device_registries( + device_manager.ListDeviceRegistriesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_device_registries_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_registries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceRegistriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceRegistriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_device_registries( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_device_registries_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_device_registries( + device_manager.ListDeviceRegistriesRequest(), + parent='parent_value', + ) + + +def test_list_device_registries_pager(transport_name: str = "grpc"): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_registries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + next_page_token='abc', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[], + next_page_token='def', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + ], + next_page_token='ghi', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_device_registries(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DeviceRegistry) + for i in results) +def test_list_device_registries_pages(transport_name: str = "grpc"): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_registries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + next_page_token='abc', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[], + next_page_token='def', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + ], + next_page_token='ghi', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + ), + RuntimeError, + ) + pages = list(client.list_device_registries(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_device_registries_async_pager(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_registries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + next_page_token='abc', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[], + next_page_token='def', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + ], + next_page_token='ghi', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_device_registries(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.DeviceRegistry) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_device_registries_async_pages(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_registries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + next_page_token='abc', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[], + next_page_token='def', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + ], + next_page_token='ghi', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_device_registries(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + device_manager.CreateDeviceRequest, + dict, +]) +def test_create_device(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device( + id='id_value', + name='name_value', + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + response = client.create_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.CreateDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.num_id == 636 + assert response.blocked is True + assert response.log_level == resources.LogLevel.NONE + + +def test_create_device_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device), + '__call__') as call: + client.create_device() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.CreateDeviceRequest() + +@pytest.mark.asyncio +async def test_create_device_async(transport: str = 'grpc_asyncio', request_type=device_manager.CreateDeviceRequest): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Device( + id='id_value', + name='name_value', + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + )) + response = await client.create_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.CreateDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.num_id == 636 + assert response.blocked is True + assert response.log_level == resources.LogLevel.NONE + + +@pytest.mark.asyncio +async def test_create_device_async_from_dict(): + await test_create_device_async(request_type=dict) + + +def test_create_device_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.CreateDeviceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device), + '__call__') as call: + call.return_value = resources.Device() + client.create_device(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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_device_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.CreateDeviceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + await client.create_device(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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_device_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_device( + parent='parent_value', + device=resources.Device(id='id_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].device + mock_val = resources.Device(id='id_value') + assert arg == mock_val + + +def test_create_device_flattened_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_device( + device_manager.CreateDeviceRequest(), + parent='parent_value', + device=resources.Device(id='id_value'), + ) + +@pytest.mark.asyncio +async def test_create_device_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_device( + parent='parent_value', + device=resources.Device(id='id_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].device + mock_val = resources.Device(id='id_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_device_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_device( + device_manager.CreateDeviceRequest(), + parent='parent_value', + device=resources.Device(id='id_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.GetDeviceRequest, + dict, +]) +def test_get_device(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + 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_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device( + id='id_value', + name='name_value', + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + response = client.get_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.GetDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.num_id == 636 + assert response.blocked is True + assert response.log_level == resources.LogLevel.NONE + + +def test_get_device_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_device), + '__call__') as call: + client.get_device() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.GetDeviceRequest() + +@pytest.mark.asyncio +async def test_get_device_async(transport: str = 'grpc_asyncio', request_type=device_manager.GetDeviceRequest): + client = DeviceManagerAsyncClient( + 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_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Device( + id='id_value', + name='name_value', + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + )) + response = await client.get_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.GetDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.num_id == 636 + assert response.blocked is True + assert response.log_level == resources.LogLevel.NONE + + +@pytest.mark.asyncio +async def test_get_device_async_from_dict(): + await test_get_device_async(request_type=dict) + + +def test_get_device_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.GetDeviceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_device), + '__call__') as call: + call.return_value = resources.Device() + client.get_device(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_device_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.GetDeviceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_device), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + await client.get_device(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_device_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_device( + 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_device_flattened_error(): + client = DeviceManagerClient( + 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_device( + device_manager.GetDeviceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_device_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_device( + 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_device_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_device( + device_manager.GetDeviceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.UpdateDeviceRequest, + dict, +]) +def test_update_device(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device( + id='id_value', + name='name_value', + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + response = client.update_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.UpdateDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.num_id == 636 + assert response.blocked is True + assert response.log_level == resources.LogLevel.NONE + + +def test_update_device_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device), + '__call__') as call: + client.update_device() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.UpdateDeviceRequest() + +@pytest.mark.asyncio +async def test_update_device_async(transport: str = 'grpc_asyncio', request_type=device_manager.UpdateDeviceRequest): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Device( + id='id_value', + name='name_value', + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + )) + response = await client.update_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.UpdateDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.num_id == 636 + assert response.blocked is True + assert response.log_level == resources.LogLevel.NONE + + +@pytest.mark.asyncio +async def test_update_device_async_from_dict(): + await test_update_device_async(request_type=dict) + + +def test_update_device_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.UpdateDeviceRequest() + + request.device.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device), + '__call__') as call: + call.return_value = resources.Device() + client.update_device(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', + 'device.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_device_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.UpdateDeviceRequest() + + request.device.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + await client.update_device(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', + 'device.name=name_value', + ) in kw['metadata'] + + +def test_update_device_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_device( + device=resources.Device(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].device + mock_val = resources.Device(id='id_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_device_flattened_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_device( + device_manager.UpdateDeviceRequest(), + device=resources.Device(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_device_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Device() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_device( + device=resources.Device(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].device + mock_val = resources.Device(id='id_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_device_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_device( + device_manager.UpdateDeviceRequest(), + device=resources.Device(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.DeleteDeviceRequest, + dict, +]) +def test_delete_device(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + 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.delete_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.DeleteDeviceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_device_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_device), + '__call__') as call: + client.delete_device() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.DeleteDeviceRequest() + +@pytest.mark.asyncio +async def test_delete_device_async(transport: str = 'grpc_asyncio', request_type=device_manager.DeleteDeviceRequest): + client = DeviceManagerAsyncClient( + 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.delete_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.DeleteDeviceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_device_async_from_dict(): + await test_delete_device_async(request_type=dict) + + +def test_delete_device_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.DeleteDeviceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_device), + '__call__') as call: + call.return_value = None + client.delete_device(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_delete_device_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.DeleteDeviceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_device), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_device(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_delete_device_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_device( + 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_delete_device_flattened_error(): + client = DeviceManagerClient( + 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.delete_device( + device_manager.DeleteDeviceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_device_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_device( + 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_delete_device_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_device( + device_manager.DeleteDeviceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.ListDevicesRequest, + dict, +]) +def test_list_devices(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_devices), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDevicesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_devices(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDevicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDevicesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_devices_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_devices), + '__call__') as call: + client.list_devices() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDevicesRequest() + +@pytest.mark.asyncio +async def test_list_devices_async(transport: str = 'grpc_asyncio', request_type=device_manager.ListDevicesRequest): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_devices), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDevicesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_devices(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDevicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDevicesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_devices_async_from_dict(): + await test_list_devices_async(request_type=dict) + + +def test_list_devices_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.ListDevicesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_devices), + '__call__') as call: + call.return_value = device_manager.ListDevicesResponse() + client.list_devices(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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_devices_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.ListDevicesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_devices), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDevicesResponse()) + await client.list_devices(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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_devices_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_devices), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDevicesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_devices( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_devices_flattened_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_devices( + device_manager.ListDevicesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_devices_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_devices), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDevicesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDevicesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_devices( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_devices_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_devices( + device_manager.ListDevicesRequest(), + parent='parent_value', + ) + + +def test_list_devices_pager(transport_name: str = "grpc"): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_devices), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + resources.Device(), + resources.Device(), + ], + next_page_token='abc', + ), + device_manager.ListDevicesResponse( + devices=[], + next_page_token='def', + ), + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + ], + next_page_token='ghi', + ), + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + resources.Device(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_devices(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Device) + for i in results) +def test_list_devices_pages(transport_name: str = "grpc"): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_devices), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + resources.Device(), + resources.Device(), + ], + next_page_token='abc', + ), + device_manager.ListDevicesResponse( + devices=[], + next_page_token='def', + ), + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + ], + next_page_token='ghi', + ), + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + resources.Device(), + ], + ), + RuntimeError, + ) + pages = list(client.list_devices(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_devices_async_pager(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_devices), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + resources.Device(), + resources.Device(), + ], + next_page_token='abc', + ), + device_manager.ListDevicesResponse( + devices=[], + next_page_token='def', + ), + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + ], + next_page_token='ghi', + ), + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + resources.Device(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_devices(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.Device) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_devices_async_pages(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_devices), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + resources.Device(), + resources.Device(), + ], + next_page_token='abc', + ), + device_manager.ListDevicesResponse( + devices=[], + next_page_token='def', + ), + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + ], + next_page_token='ghi', + ), + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + resources.Device(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_devices(request={})).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + device_manager.ModifyCloudToDeviceConfigRequest, + dict, +]) +def test_modify_cloud_to_device_config(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + 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.modify_cloud_to_device_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceConfig( + version=774, + binary_data=b'binary_data_blob', + ) + response = client.modify_cloud_to_device_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ModifyCloudToDeviceConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceConfig) + assert response.version == 774 + assert response.binary_data == b'binary_data_blob' + + +def test_modify_cloud_to_device_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_cloud_to_device_config), + '__call__') as call: + client.modify_cloud_to_device_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ModifyCloudToDeviceConfigRequest() + +@pytest.mark.asyncio +async def test_modify_cloud_to_device_config_async(transport: str = 'grpc_asyncio', request_type=device_manager.ModifyCloudToDeviceConfigRequest): + client = DeviceManagerAsyncClient( + 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.modify_cloud_to_device_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceConfig( + version=774, + binary_data=b'binary_data_blob', + )) + response = await client.modify_cloud_to_device_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ModifyCloudToDeviceConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceConfig) + assert response.version == 774 + assert response.binary_data == b'binary_data_blob' + + +@pytest.mark.asyncio +async def test_modify_cloud_to_device_config_async_from_dict(): + await test_modify_cloud_to_device_config_async(request_type=dict) + + +def test_modify_cloud_to_device_config_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.ModifyCloudToDeviceConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_cloud_to_device_config), + '__call__') as call: + call.return_value = resources.DeviceConfig() + client.modify_cloud_to_device_config(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_modify_cloud_to_device_config_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.ModifyCloudToDeviceConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_cloud_to_device_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceConfig()) + await client.modify_cloud_to_device_config(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_modify_cloud_to_device_config_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_cloud_to_device_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.modify_cloud_to_device_config( + name='name_value', + binary_data=b'binary_data_blob', + ) + + # 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 + arg = args[0].binary_data + mock_val = b'binary_data_blob' + assert arg == mock_val + + +def test_modify_cloud_to_device_config_flattened_error(): + client = DeviceManagerClient( + 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.modify_cloud_to_device_config( + device_manager.ModifyCloudToDeviceConfigRequest(), + name='name_value', + binary_data=b'binary_data_blob', + ) + +@pytest.mark.asyncio +async def test_modify_cloud_to_device_config_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.modify_cloud_to_device_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DeviceConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.modify_cloud_to_device_config( + name='name_value', + binary_data=b'binary_data_blob', + ) + + # 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 + arg = args[0].binary_data + mock_val = b'binary_data_blob' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_modify_cloud_to_device_config_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.modify_cloud_to_device_config( + device_manager.ModifyCloudToDeviceConfigRequest(), + name='name_value', + binary_data=b'binary_data_blob', + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.ListDeviceConfigVersionsRequest, + dict, +]) +def test_list_device_config_versions(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_config_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceConfigVersionsResponse( + ) + response = client.list_device_config_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDeviceConfigVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.ListDeviceConfigVersionsResponse) + + +def test_list_device_config_versions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_config_versions), + '__call__') as call: + client.list_device_config_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDeviceConfigVersionsRequest() + +@pytest.mark.asyncio +async def test_list_device_config_versions_async(transport: str = 'grpc_asyncio', request_type=device_manager.ListDeviceConfigVersionsRequest): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_config_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceConfigVersionsResponse( + )) + response = await client.list_device_config_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDeviceConfigVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.ListDeviceConfigVersionsResponse) + + +@pytest.mark.asyncio +async def test_list_device_config_versions_async_from_dict(): + await test_list_device_config_versions_async(request_type=dict) + + +def test_list_device_config_versions_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.ListDeviceConfigVersionsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_config_versions), + '__call__') as call: + call.return_value = device_manager.ListDeviceConfigVersionsResponse() + client.list_device_config_versions(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_list_device_config_versions_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.ListDeviceConfigVersionsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_config_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceConfigVersionsResponse()) + await client.list_device_config_versions(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_list_device_config_versions_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_config_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceConfigVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_device_config_versions( + 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_list_device_config_versions_flattened_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_device_config_versions( + device_manager.ListDeviceConfigVersionsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_list_device_config_versions_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_config_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceConfigVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceConfigVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_device_config_versions( + 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_list_device_config_versions_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_device_config_versions( + device_manager.ListDeviceConfigVersionsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.ListDeviceStatesRequest, + dict, +]) +def test_list_device_states(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_states), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceStatesResponse( + ) + response = client.list_device_states(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDeviceStatesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.ListDeviceStatesResponse) + + +def test_list_device_states_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_states), + '__call__') as call: + client.list_device_states() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDeviceStatesRequest() + +@pytest.mark.asyncio +async def test_list_device_states_async(transport: str = 'grpc_asyncio', request_type=device_manager.ListDeviceStatesRequest): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_states), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceStatesResponse( + )) + response = await client.list_device_states(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.ListDeviceStatesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.ListDeviceStatesResponse) + + +@pytest.mark.asyncio +async def test_list_device_states_async_from_dict(): + await test_list_device_states_async(request_type=dict) + + +def test_list_device_states_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.ListDeviceStatesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_states), + '__call__') as call: + call.return_value = device_manager.ListDeviceStatesResponse() + client.list_device_states(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_list_device_states_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.ListDeviceStatesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_states), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceStatesResponse()) + await client.list_device_states(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_list_device_states_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_states), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceStatesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_device_states( + 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_list_device_states_flattened_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_device_states( + device_manager.ListDeviceStatesRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_list_device_states_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_device_states), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.ListDeviceStatesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceStatesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_device_states( + 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_list_device_states_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_device_states( + device_manager.ListDeviceStatesRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + 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.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_set_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DeviceManagerAsyncClient( + 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.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( + version=774, + etag=b'etag_blob', + )) + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = DeviceManagerClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(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', + 'resource=resource_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.set_iam_policy(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', + 'resource=resource_value', + ) in kw['metadata'] + +def test_set_iam_policy_from_dict_foreign(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.set_iam_policy(request={ + 'resource': 'resource_value', + 'policy': policy_pb2.Policy(version=774), + 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_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].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = DeviceManagerClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_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].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + 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_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_get_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DeviceManagerAsyncClient( + 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_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( + version=774, + etag=b'etag_blob', + )) + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = DeviceManagerClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(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', + 'resource=resource_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.get_iam_policy(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', + 'resource=resource_value', + ) in kw['metadata'] + +def test_get_iam_policy_from_dict_foreign(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.get_iam_policy(request={ + 'resource': 'resource_value', + 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_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].resource + mock_val = 'resource_value' + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = DeviceManagerClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_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].resource + mock_val = 'resource_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + 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.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ['permissions_value'] + + +def test_test_iam_permissions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DeviceManagerAsyncClient( + 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.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + )) + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ['permissions_value'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = DeviceManagerClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(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', + 'resource=resource_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + await client.test_iam_permissions(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', + 'resource=resource_value', + ) in kw['metadata'] + +def test_test_iam_permissions_from_dict_foreign(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + response = client.test_iam_permissions(request={ + 'resource': 'resource_value', + 'permissions': ['permissions_value'], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_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].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = DeviceManagerClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_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].resource + mock_val = 'resource_value' + assert arg == mock_val + arg = args[0].permissions + mock_val = ['permissions_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.SendCommandToDeviceRequest, + dict, +]) +def test_send_command_to_device(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + 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.send_command_to_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.SendCommandToDeviceResponse( + ) + response = client.send_command_to_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.SendCommandToDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.SendCommandToDeviceResponse) + + +def test_send_command_to_device_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_command_to_device), + '__call__') as call: + client.send_command_to_device() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.SendCommandToDeviceRequest() + +@pytest.mark.asyncio +async def test_send_command_to_device_async(transport: str = 'grpc_asyncio', request_type=device_manager.SendCommandToDeviceRequest): + client = DeviceManagerAsyncClient( + 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.send_command_to_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.SendCommandToDeviceResponse( + )) + response = await client.send_command_to_device(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.SendCommandToDeviceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.SendCommandToDeviceResponse) + + +@pytest.mark.asyncio +async def test_send_command_to_device_async_from_dict(): + await test_send_command_to_device_async(request_type=dict) + + +def test_send_command_to_device_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.SendCommandToDeviceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_command_to_device), + '__call__') as call: + call.return_value = device_manager.SendCommandToDeviceResponse() + client.send_command_to_device(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_send_command_to_device_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.SendCommandToDeviceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_command_to_device), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.SendCommandToDeviceResponse()) + await client.send_command_to_device(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_send_command_to_device_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_command_to_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.SendCommandToDeviceResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.send_command_to_device( + name='name_value', + binary_data=b'binary_data_blob', + subfolder='subfolder_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 + arg = args[0].binary_data + mock_val = b'binary_data_blob' + assert arg == mock_val + arg = args[0].subfolder + mock_val = 'subfolder_value' + assert arg == mock_val + + +def test_send_command_to_device_flattened_error(): + client = DeviceManagerClient( + 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.send_command_to_device( + device_manager.SendCommandToDeviceRequest(), + name='name_value', + binary_data=b'binary_data_blob', + subfolder='subfolder_value', + ) + +@pytest.mark.asyncio +async def test_send_command_to_device_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.send_command_to_device), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.SendCommandToDeviceResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.SendCommandToDeviceResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.send_command_to_device( + name='name_value', + binary_data=b'binary_data_blob', + subfolder='subfolder_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 + arg = args[0].binary_data + mock_val = b'binary_data_blob' + assert arg == mock_val + arg = args[0].subfolder + mock_val = 'subfolder_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_send_command_to_device_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.send_command_to_device( + device_manager.SendCommandToDeviceRequest(), + name='name_value', + binary_data=b'binary_data_blob', + subfolder='subfolder_value', + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.BindDeviceToGatewayRequest, + dict, +]) +def test_bind_device_to_gateway(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + 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.bind_device_to_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.BindDeviceToGatewayResponse( + ) + response = client.bind_device_to_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.BindDeviceToGatewayRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.BindDeviceToGatewayResponse) + + +def test_bind_device_to_gateway_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bind_device_to_gateway), + '__call__') as call: + client.bind_device_to_gateway() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.BindDeviceToGatewayRequest() + +@pytest.mark.asyncio +async def test_bind_device_to_gateway_async(transport: str = 'grpc_asyncio', request_type=device_manager.BindDeviceToGatewayRequest): + client = DeviceManagerAsyncClient( + 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.bind_device_to_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.BindDeviceToGatewayResponse( + )) + response = await client.bind_device_to_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.BindDeviceToGatewayRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.BindDeviceToGatewayResponse) + + +@pytest.mark.asyncio +async def test_bind_device_to_gateway_async_from_dict(): + await test_bind_device_to_gateway_async(request_type=dict) + + +def test_bind_device_to_gateway_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.BindDeviceToGatewayRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bind_device_to_gateway), + '__call__') as call: + call.return_value = device_manager.BindDeviceToGatewayResponse() + client.bind_device_to_gateway(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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_bind_device_to_gateway_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.BindDeviceToGatewayRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bind_device_to_gateway), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.BindDeviceToGatewayResponse()) + await client.bind_device_to_gateway(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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_bind_device_to_gateway_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bind_device_to_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.BindDeviceToGatewayResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.bind_device_to_gateway( + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].gateway_id + mock_val = 'gateway_id_value' + assert arg == mock_val + arg = args[0].device_id + mock_val = 'device_id_value' + assert arg == mock_val + + +def test_bind_device_to_gateway_flattened_error(): + client = DeviceManagerClient( + 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.bind_device_to_gateway( + device_manager.BindDeviceToGatewayRequest(), + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + +@pytest.mark.asyncio +async def test_bind_device_to_gateway_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bind_device_to_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.BindDeviceToGatewayResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.BindDeviceToGatewayResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.bind_device_to_gateway( + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].gateway_id + mock_val = 'gateway_id_value' + assert arg == mock_val + arg = args[0].device_id + mock_val = 'device_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_bind_device_to_gateway_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.bind_device_to_gateway( + device_manager.BindDeviceToGatewayRequest(), + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.UnbindDeviceFromGatewayRequest, + dict, +]) +def test_unbind_device_from_gateway(request_type, transport: str = 'grpc'): + client = DeviceManagerClient( + 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.unbind_device_from_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.UnbindDeviceFromGatewayResponse( + ) + response = client.unbind_device_from_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.UnbindDeviceFromGatewayRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.UnbindDeviceFromGatewayResponse) + + +def test_unbind_device_from_gateway_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unbind_device_from_gateway), + '__call__') as call: + client.unbind_device_from_gateway() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.UnbindDeviceFromGatewayRequest() + +@pytest.mark.asyncio +async def test_unbind_device_from_gateway_async(transport: str = 'grpc_asyncio', request_type=device_manager.UnbindDeviceFromGatewayRequest): + client = DeviceManagerAsyncClient( + 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.unbind_device_from_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.UnbindDeviceFromGatewayResponse( + )) + response = await client.unbind_device_from_gateway(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == device_manager.UnbindDeviceFromGatewayRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.UnbindDeviceFromGatewayResponse) + + +@pytest.mark.asyncio +async def test_unbind_device_from_gateway_async_from_dict(): + await test_unbind_device_from_gateway_async(request_type=dict) + + +def test_unbind_device_from_gateway_field_headers(): + client = DeviceManagerClient( + 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 = device_manager.UnbindDeviceFromGatewayRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unbind_device_from_gateway), + '__call__') as call: + call.return_value = device_manager.UnbindDeviceFromGatewayResponse() + client.unbind_device_from_gateway(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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_unbind_device_from_gateway_field_headers_async(): + client = DeviceManagerAsyncClient( + 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 = device_manager.UnbindDeviceFromGatewayRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unbind_device_from_gateway), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.UnbindDeviceFromGatewayResponse()) + await client.unbind_device_from_gateway(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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_unbind_device_from_gateway_flattened(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unbind_device_from_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.UnbindDeviceFromGatewayResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.unbind_device_from_gateway( + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].gateway_id + mock_val = 'gateway_id_value' + assert arg == mock_val + arg = args[0].device_id + mock_val = 'device_id_value' + assert arg == mock_val + + +def test_unbind_device_from_gateway_flattened_error(): + client = DeviceManagerClient( + 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.unbind_device_from_gateway( + device_manager.UnbindDeviceFromGatewayRequest(), + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + +@pytest.mark.asyncio +async def test_unbind_device_from_gateway_flattened_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unbind_device_from_gateway), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = device_manager.UnbindDeviceFromGatewayResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.UnbindDeviceFromGatewayResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.unbind_device_from_gateway( + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].gateway_id + mock_val = 'gateway_id_value' + assert arg == mock_val + arg = args[0].device_id + mock_val = 'device_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_unbind_device_from_gateway_flattened_error_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.unbind_device_from_gateway( + device_manager.UnbindDeviceFromGatewayRequest(), + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.CreateDeviceRegistryRequest, + dict, +]) +def test_create_device_registry_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["device_registry"] = {'id': 'id_value', 'name': 'name_value', 'event_notification_configs': [{'subfolder_matches': 'subfolder_matches_value', 'pubsub_topic_name': 'pubsub_topic_name_value'}], 'state_notification_config': {'pubsub_topic_name': 'pubsub_topic_name_value'}, 'mqtt_config': {'mqtt_enabled_state': 1}, 'http_config': {'http_enabled_state': 1}, 'log_level': 10, 'credentials': [{'public_key_certificate': {'format_': 1, 'certificate': 'certificate_value', 'x509_details': {'issuer': 'issuer_value', 'subject': 'subject_value', 'start_time': {'seconds': 751, 'nanos': 543}, 'expiry_time': {}, 'signature_algorithm': 'signature_algorithm_value', 'public_key_type': 'public_key_type_value'}}}]} + 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 = resources.DeviceRegistry( + id='id_value', + name='name_value', + log_level=resources.LogLevel.NONE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.DeviceRegistry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_device_registry(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.log_level == resources.LogLevel.NONE + + +def test_create_device_registry_rest_required_fields(request_type=device_manager.CreateDeviceRegistryRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_device_registry._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_device_registry._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DeviceRegistry() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.DeviceRegistry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_device_registry(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_device_registry_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_device_registry._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "deviceRegistry", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_device_registry_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_create_device_registry") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_create_device_registry") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.CreateDeviceRegistryRequest.pb(device_manager.CreateDeviceRegistryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.DeviceRegistry.to_json(resources.DeviceRegistry()) + + request = device_manager.CreateDeviceRegistryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DeviceRegistry() + + client.create_device_registry(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_device_registry_rest_bad_request(transport: str = 'rest', request_type=device_manager.CreateDeviceRegistryRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["device_registry"] = {'id': 'id_value', 'name': 'name_value', 'event_notification_configs': [{'subfolder_matches': 'subfolder_matches_value', 'pubsub_topic_name': 'pubsub_topic_name_value'}], 'state_notification_config': {'pubsub_topic_name': 'pubsub_topic_name_value'}, 'mqtt_config': {'mqtt_enabled_state': 1}, 'http_config': {'http_enabled_state': 1}, 'log_level': 10, 'credentials': [{'public_key_certificate': {'format_': 1, 'certificate': 'certificate_value', 'x509_details': {'issuer': 'issuer_value', 'subject': 'subject_value', 'start_time': {'seconds': 751, 'nanos': 543}, 'expiry_time': {}, 'signature_algorithm': 'signature_algorithm_value', 'public_key_type': 'public_key_type_value'}}}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_device_registry(request) + + +def test_create_device_registry_rest_flattened(): + client = DeviceManagerClient( + 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 = resources.DeviceRegistry() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + device_registry=resources.DeviceRegistry(id='id_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.DeviceRegistry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_device_registry(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/registries" % client.transport._host, args[1]) + + +def test_create_device_registry_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_device_registry( + device_manager.CreateDeviceRegistryRequest(), + parent='parent_value', + device_registry=resources.DeviceRegistry(id='id_value'), + ) + + +def test_create_device_registry_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.GetDeviceRegistryRequest, + dict, +]) +def test_get_device_registry_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3'} + 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 = resources.DeviceRegistry( + id='id_value', + name='name_value', + log_level=resources.LogLevel.NONE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.DeviceRegistry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_device_registry(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.log_level == resources.LogLevel.NONE + + +def test_get_device_registry_rest_required_fields(request_type=device_manager.GetDeviceRegistryRequest): + transport_class = transports.DeviceManagerRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_device_registry._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_device_registry._get_unset_required_fields(jsonified_request) + 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 = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DeviceRegistry() + # 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 + + pb_return_value = resources.DeviceRegistry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_device_registry(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_device_registry_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_device_registry._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_device_registry_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_get_device_registry") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_get_device_registry") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.GetDeviceRegistryRequest.pb(device_manager.GetDeviceRegistryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.DeviceRegistry.to_json(resources.DeviceRegistry()) + + request = device_manager.GetDeviceRegistryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DeviceRegistry() + + client.get_device_registry(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_device_registry_rest_bad_request(transport: str = 'rest', request_type=device_manager.GetDeviceRegistryRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_device_registry(request) + + +def test_get_device_registry_rest_flattened(): + client = DeviceManagerClient( + 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 = resources.DeviceRegistry() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3'} + + # 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 + pb_return_value = resources.DeviceRegistry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_device_registry(**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=projects/*/locations/*/registries/*}" % client.transport._host, args[1]) + + +def test_get_device_registry_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + 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_device_registry( + device_manager.GetDeviceRegistryRequest(), + name='name_value', + ) + + +def test_get_device_registry_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.UpdateDeviceRegistryRequest, + dict, +]) +def test_update_device_registry_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'device_registry': {'name': 'projects/sample1/locations/sample2/registries/sample3'}} + request_init["device_registry"] = {'id': 'id_value', 'name': 'projects/sample1/locations/sample2/registries/sample3', 'event_notification_configs': [{'subfolder_matches': 'subfolder_matches_value', 'pubsub_topic_name': 'pubsub_topic_name_value'}], 'state_notification_config': {'pubsub_topic_name': 'pubsub_topic_name_value'}, 'mqtt_config': {'mqtt_enabled_state': 1}, 'http_config': {'http_enabled_state': 1}, 'log_level': 10, 'credentials': [{'public_key_certificate': {'format_': 1, 'certificate': 'certificate_value', 'x509_details': {'issuer': 'issuer_value', 'subject': 'subject_value', 'start_time': {'seconds': 751, 'nanos': 543}, 'expiry_time': {}, 'signature_algorithm': 'signature_algorithm_value', 'public_key_type': 'public_key_type_value'}}}]} + 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 = resources.DeviceRegistry( + id='id_value', + name='name_value', + log_level=resources.LogLevel.NONE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.DeviceRegistry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_device_registry(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceRegistry) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.log_level == resources.LogLevel.NONE + + +def test_update_device_registry_rest_required_fields(request_type=device_manager.UpdateDeviceRegistryRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_device_registry._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_device_registry._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DeviceRegistry() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.DeviceRegistry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_device_registry(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_device_registry_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_device_registry._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("deviceRegistry", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_device_registry_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_update_device_registry") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_update_device_registry") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.UpdateDeviceRegistryRequest.pb(device_manager.UpdateDeviceRegistryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.DeviceRegistry.to_json(resources.DeviceRegistry()) + + request = device_manager.UpdateDeviceRegistryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DeviceRegistry() + + client.update_device_registry(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_device_registry_rest_bad_request(transport: str = 'rest', request_type=device_manager.UpdateDeviceRegistryRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'device_registry': {'name': 'projects/sample1/locations/sample2/registries/sample3'}} + request_init["device_registry"] = {'id': 'id_value', 'name': 'projects/sample1/locations/sample2/registries/sample3', 'event_notification_configs': [{'subfolder_matches': 'subfolder_matches_value', 'pubsub_topic_name': 'pubsub_topic_name_value'}], 'state_notification_config': {'pubsub_topic_name': 'pubsub_topic_name_value'}, 'mqtt_config': {'mqtt_enabled_state': 1}, 'http_config': {'http_enabled_state': 1}, 'log_level': 10, 'credentials': [{'public_key_certificate': {'format_': 1, 'certificate': 'certificate_value', 'x509_details': {'issuer': 'issuer_value', 'subject': 'subject_value', 'start_time': {'seconds': 751, 'nanos': 543}, 'expiry_time': {}, 'signature_algorithm': 'signature_algorithm_value', 'public_key_type': 'public_key_type_value'}}}]} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_device_registry(request) + + +def test_update_device_registry_rest_flattened(): + client = DeviceManagerClient( + 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 = resources.DeviceRegistry() + + # get arguments that satisfy an http rule for this method + sample_request = {'device_registry': {'name': 'projects/sample1/locations/sample2/registries/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + device_registry=resources.DeviceRegistry(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.DeviceRegistry.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_device_registry(**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/{device_registry.name=projects/*/locations/*/registries/*}" % client.transport._host, args[1]) + + +def test_update_device_registry_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_device_registry( + device_manager.UpdateDeviceRegistryRequest(), + device_registry=resources.DeviceRegistry(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_device_registry_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.DeleteDeviceRegistryRequest, + dict, +]) +def test_delete_device_registry_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3'} + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_device_registry(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_device_registry_rest_required_fields(request_type=device_manager.DeleteDeviceRegistryRequest): + transport_class = transports.DeviceManagerRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_device_registry._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()).delete_device_registry._get_unset_required_fields(jsonified_request) + 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 = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_device_registry(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_device_registry_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_device_registry._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_device_registry_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "pre_delete_device_registry") as pre: + pre.assert_not_called() + pb_message = device_manager.DeleteDeviceRegistryRequest.pb(device_manager.DeleteDeviceRegistryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = device_manager.DeleteDeviceRegistryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_device_registry(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_device_registry_rest_bad_request(transport: str = 'rest', request_type=device_manager.DeleteDeviceRegistryRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_device_registry(request) + + +def test_delete_device_registry_rest_flattened(): + client = DeviceManagerClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3'} + + # 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 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_device_registry(**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=projects/*/locations/*/registries/*}" % client.transport._host, args[1]) + + +def test_delete_device_registry_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + 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.delete_device_registry( + device_manager.DeleteDeviceRegistryRequest(), + name='name_value', + ) + + +def test_delete_device_registry_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.ListDeviceRegistriesRequest, + dict, +]) +def test_list_device_registries_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = device_manager.ListDeviceRegistriesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.ListDeviceRegistriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_device_registries(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeviceRegistriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_device_registries_rest_required_fields(request_type=device_manager.ListDeviceRegistriesRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_device_registries._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_device_registries._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = device_manager.ListDeviceRegistriesResponse() + # 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 + + pb_return_value = device_manager.ListDeviceRegistriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_device_registries(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_device_registries_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_device_registries._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_device_registries_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_list_device_registries") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_list_device_registries") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.ListDeviceRegistriesRequest.pb(device_manager.ListDeviceRegistriesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = device_manager.ListDeviceRegistriesResponse.to_json(device_manager.ListDeviceRegistriesResponse()) + + request = device_manager.ListDeviceRegistriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = device_manager.ListDeviceRegistriesResponse() + + client.list_device_registries(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_device_registries_rest_bad_request(transport: str = 'rest', request_type=device_manager.ListDeviceRegistriesRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_device_registries(request) + + +def test_list_device_registries_rest_flattened(): + client = DeviceManagerClient( + 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 = device_manager.ListDeviceRegistriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.ListDeviceRegistriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_device_registries(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/registries" % client.transport._host, args[1]) + + +def test_list_device_registries_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_device_registries( + device_manager.ListDeviceRegistriesRequest(), + parent='parent_value', + ) + + +def test_list_device_registries_rest_pager(transport: str = 'rest'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + next_page_token='abc', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[], + next_page_token='def', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + ], + next_page_token='ghi', + ), + device_manager.ListDeviceRegistriesResponse( + device_registries=[ + resources.DeviceRegistry(), + resources.DeviceRegistry(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(device_manager.ListDeviceRegistriesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_device_registries(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DeviceRegistry) + for i in results) + + pages = list(client.list_device_registries(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + device_manager.CreateDeviceRequest, + dict, +]) +def test_create_device_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + request_init["device"] = {'id': 'id_value', 'name': 'name_value', 'num_id': 636, 'credentials': [{'public_key': {'format_': 3, 'key': 'key_value'}, 'expiration_time': {'seconds': 751, 'nanos': 543}}], 'last_heartbeat_time': {}, 'last_event_time': {}, 'last_state_time': {}, 'last_config_ack_time': {}, 'last_config_send_time': {}, 'blocked': True, 'last_error_time': {}, 'last_error_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'config': {'version': 774, 'cloud_update_time': {}, 'device_ack_time': {}, 'binary_data': b'binary_data_blob'}, 'state': {'update_time': {}, 'binary_data': b'binary_data_blob'}, 'log_level': 10, 'metadata': {}, 'gateway_config': {'gateway_type': 1, 'gateway_auth_method': 1, 'last_accessed_gateway_id': 'last_accessed_gateway_id_value', 'last_accessed_gateway_time': {}}} + 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 = resources.Device( + id='id_value', + name='name_value', + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Device.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_device(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.num_id == 636 + assert response.blocked is True + assert response.log_level == resources.LogLevel.NONE + + +def test_create_device_rest_required_fields(request_type=device_manager.CreateDeviceRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_device._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_device._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Device() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Device.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_device(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_device_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_device._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "device", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_device_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_create_device") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_create_device") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.CreateDeviceRequest.pb(device_manager.CreateDeviceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Device.to_json(resources.Device()) + + request = device_manager.CreateDeviceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Device() + + client.create_device(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_device_rest_bad_request(transport: str = 'rest', request_type=device_manager.CreateDeviceRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + request_init["device"] = {'id': 'id_value', 'name': 'name_value', 'num_id': 636, 'credentials': [{'public_key': {'format_': 3, 'key': 'key_value'}, 'expiration_time': {'seconds': 751, 'nanos': 543}}], 'last_heartbeat_time': {}, 'last_event_time': {}, 'last_state_time': {}, 'last_config_ack_time': {}, 'last_config_send_time': {}, 'blocked': True, 'last_error_time': {}, 'last_error_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'config': {'version': 774, 'cloud_update_time': {}, 'device_ack_time': {}, 'binary_data': b'binary_data_blob'}, 'state': {'update_time': {}, 'binary_data': b'binary_data_blob'}, 'log_level': 10, 'metadata': {}, 'gateway_config': {'gateway_type': 1, 'gateway_auth_method': 1, 'last_accessed_gateway_id': 'last_accessed_gateway_id_value', 'last_accessed_gateway_time': {}}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_device(request) + + +def test_create_device_rest_flattened(): + client = DeviceManagerClient( + 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 = resources.Device() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + device=resources.Device(id='id_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Device.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_device(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/registries/*}/devices" % client.transport._host, args[1]) + + +def test_create_device_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_device( + device_manager.CreateDeviceRequest(), + parent='parent_value', + device=resources.Device(id='id_value'), + ) + + +def test_create_device_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.GetDeviceRequest, + dict, +]) +def test_get_device_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + 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 = resources.Device( + id='id_value', + name='name_value', + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Device.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_device(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.num_id == 636 + assert response.blocked is True + assert response.log_level == resources.LogLevel.NONE + + +def test_get_device_rest_required_fields(request_type=device_manager.GetDeviceRequest): + transport_class = transports.DeviceManagerRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_device._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_device._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("field_mask", )) + 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 = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Device() + # 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 + + pb_return_value = resources.Device.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_device(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_device_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_device._get_unset_required_fields({}) + assert set(unset_fields) == (set(("fieldMask", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_device_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_get_device") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_get_device") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.GetDeviceRequest.pb(device_manager.GetDeviceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Device.to_json(resources.Device()) + + request = device_manager.GetDeviceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Device() + + client.get_device(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_device_rest_bad_request(transport: str = 'rest', request_type=device_manager.GetDeviceRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_device(request) + + +def test_get_device_rest_flattened(): + client = DeviceManagerClient( + 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 = resources.Device() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + + # 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 + pb_return_value = resources.Device.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_device(**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=projects/*/locations/*/registries/*/devices/*}" % client.transport._host, args[1]) + + +def test_get_device_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + 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_device( + device_manager.GetDeviceRequest(), + name='name_value', + ) + + +def test_get_device_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.UpdateDeviceRequest, + dict, +]) +def test_update_device_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'device': {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'}} + request_init["device"] = {'id': 'id_value', 'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4', 'num_id': 636, 'credentials': [{'public_key': {'format_': 3, 'key': 'key_value'}, 'expiration_time': {'seconds': 751, 'nanos': 543}}], 'last_heartbeat_time': {}, 'last_event_time': {}, 'last_state_time': {}, 'last_config_ack_time': {}, 'last_config_send_time': {}, 'blocked': True, 'last_error_time': {}, 'last_error_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'config': {'version': 774, 'cloud_update_time': {}, 'device_ack_time': {}, 'binary_data': b'binary_data_blob'}, 'state': {'update_time': {}, 'binary_data': b'binary_data_blob'}, 'log_level': 10, 'metadata': {}, 'gateway_config': {'gateway_type': 1, 'gateway_auth_method': 1, 'last_accessed_gateway_id': 'last_accessed_gateway_id_value', 'last_accessed_gateway_time': {}}} + 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 = resources.Device( + id='id_value', + name='name_value', + num_id=636, + blocked=True, + log_level=resources.LogLevel.NONE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Device.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_device(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Device) + assert response.id == 'id_value' + assert response.name == 'name_value' + assert response.num_id == 636 + assert response.blocked is True + assert response.log_level == resources.LogLevel.NONE + + +def test_update_device_rest_required_fields(request_type=device_manager.UpdateDeviceRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_device._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_device._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Device() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Device.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_device(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_device_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_device._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("device", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_device_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_update_device") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_update_device") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.UpdateDeviceRequest.pb(device_manager.UpdateDeviceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Device.to_json(resources.Device()) + + request = device_manager.UpdateDeviceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Device() + + client.update_device(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_device_rest_bad_request(transport: str = 'rest', request_type=device_manager.UpdateDeviceRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'device': {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'}} + request_init["device"] = {'id': 'id_value', 'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4', 'num_id': 636, 'credentials': [{'public_key': {'format_': 3, 'key': 'key_value'}, 'expiration_time': {'seconds': 751, 'nanos': 543}}], 'last_heartbeat_time': {}, 'last_event_time': {}, 'last_state_time': {}, 'last_config_ack_time': {}, 'last_config_send_time': {}, 'blocked': True, 'last_error_time': {}, 'last_error_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'config': {'version': 774, 'cloud_update_time': {}, 'device_ack_time': {}, 'binary_data': b'binary_data_blob'}, 'state': {'update_time': {}, 'binary_data': b'binary_data_blob'}, 'log_level': 10, 'metadata': {}, 'gateway_config': {'gateway_type': 1, 'gateway_auth_method': 1, 'last_accessed_gateway_id': 'last_accessed_gateway_id_value', 'last_accessed_gateway_time': {}}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_device(request) + + +def test_update_device_rest_flattened(): + client = DeviceManagerClient( + 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 = resources.Device() + + # get arguments that satisfy an http rule for this method + sample_request = {'device': {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + device=resources.Device(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Device.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_device(**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/{device.name=projects/*/locations/*/registries/*/devices/*}" % client.transport._host, args[1]) + + +def test_update_device_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_device( + device_manager.UpdateDeviceRequest(), + device=resources.Device(id='id_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_device_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.DeleteDeviceRequest, + dict, +]) +def test_delete_device_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_device(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_device_rest_required_fields(request_type=device_manager.DeleteDeviceRequest): + transport_class = transports.DeviceManagerRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_device._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()).delete_device._get_unset_required_fields(jsonified_request) + 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 = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_device(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_device_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_device._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_device_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "pre_delete_device") as pre: + pre.assert_not_called() + pb_message = device_manager.DeleteDeviceRequest.pb(device_manager.DeleteDeviceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = device_manager.DeleteDeviceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_device(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_device_rest_bad_request(transport: str = 'rest', request_type=device_manager.DeleteDeviceRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_device(request) + + +def test_delete_device_rest_flattened(): + client = DeviceManagerClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + + # 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 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_device(**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=projects/*/locations/*/registries/*/devices/*}" % client.transport._host, args[1]) + + +def test_delete_device_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + 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.delete_device( + device_manager.DeleteDeviceRequest(), + name='name_value', + ) + + +def test_delete_device_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.ListDevicesRequest, + dict, +]) +def test_list_devices_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + 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 = device_manager.ListDevicesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.ListDevicesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_devices(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDevicesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_devices_rest_required_fields(request_type=device_manager.ListDevicesRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_devices._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_devices._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("device_ids", "device_num_ids", "field_mask", "gateway_list_options", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = device_manager.ListDevicesResponse() + # 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 + + pb_return_value = device_manager.ListDevicesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_devices(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_devices_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_devices._get_unset_required_fields({}) + assert set(unset_fields) == (set(("deviceIds", "deviceNumIds", "fieldMask", "gatewayListOptions", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_devices_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_list_devices") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_list_devices") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.ListDevicesRequest.pb(device_manager.ListDevicesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = device_manager.ListDevicesResponse.to_json(device_manager.ListDevicesResponse()) + + request = device_manager.ListDevicesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = device_manager.ListDevicesResponse() + + client.list_devices(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_devices_rest_bad_request(transport: str = 'rest', request_type=device_manager.ListDevicesRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_devices(request) + + +def test_list_devices_rest_flattened(): + client = DeviceManagerClient( + 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 = device_manager.ListDevicesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.ListDevicesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_devices(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/registries/*}/devices" % client.transport._host, args[1]) + + +def test_list_devices_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_devices( + device_manager.ListDevicesRequest(), + parent='parent_value', + ) + + +def test_list_devices_rest_pager(transport: str = 'rest'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + resources.Device(), + resources.Device(), + ], + next_page_token='abc', + ), + device_manager.ListDevicesResponse( + devices=[], + next_page_token='def', + ), + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + ], + next_page_token='ghi', + ), + device_manager.ListDevicesResponse( + devices=[ + resources.Device(), + resources.Device(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(device_manager.ListDevicesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + + pager = client.list_devices(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Device) + for i in results) + + pages = list(client.list_devices(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + device_manager.ModifyCloudToDeviceConfigRequest, + dict, +]) +def test_modify_cloud_to_device_config_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + 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 = resources.DeviceConfig( + version=774, + binary_data=b'binary_data_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.DeviceConfig.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.modify_cloud_to_device_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DeviceConfig) + assert response.version == 774 + assert response.binary_data == b'binary_data_blob' + + +def test_modify_cloud_to_device_config_rest_required_fields(request_type=device_manager.ModifyCloudToDeviceConfigRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request_init["name"] = "" + request_init["binary_data"] = b'' + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).modify_cloud_to_device_config._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' + jsonified_request["binaryData"] = b'binary_data_blob' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).modify_cloud_to_device_config._get_unset_required_fields(jsonified_request) + 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' + assert "binaryData" in jsonified_request + assert jsonified_request["binaryData"] == b'binary_data_blob' + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DeviceConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.DeviceConfig.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.modify_cloud_to_device_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_modify_cloud_to_device_config_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.modify_cloud_to_device_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "binaryData", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_modify_cloud_to_device_config_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_modify_cloud_to_device_config") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_modify_cloud_to_device_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.ModifyCloudToDeviceConfigRequest.pb(device_manager.ModifyCloudToDeviceConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.DeviceConfig.to_json(resources.DeviceConfig()) + + request = device_manager.ModifyCloudToDeviceConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DeviceConfig() + + client.modify_cloud_to_device_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_modify_cloud_to_device_config_rest_bad_request(transport: str = 'rest', request_type=device_manager.ModifyCloudToDeviceConfigRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.modify_cloud_to_device_config(request) + + +def test_modify_cloud_to_device_config_rest_flattened(): + client = DeviceManagerClient( + 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 = resources.DeviceConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + binary_data=b'binary_data_blob', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.DeviceConfig.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.modify_cloud_to_device_config(**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=projects/*/locations/*/registries/*/devices/*}:modifyCloudToDeviceConfig" % client.transport._host, args[1]) + + +def test_modify_cloud_to_device_config_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + 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.modify_cloud_to_device_config( + device_manager.ModifyCloudToDeviceConfigRequest(), + name='name_value', + binary_data=b'binary_data_blob', + ) + + +def test_modify_cloud_to_device_config_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.ListDeviceConfigVersionsRequest, + dict, +]) +def test_list_device_config_versions_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + 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 = device_manager.ListDeviceConfigVersionsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.ListDeviceConfigVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_device_config_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.ListDeviceConfigVersionsResponse) + + +def test_list_device_config_versions_rest_required_fields(request_type=device_manager.ListDeviceConfigVersionsRequest): + transport_class = transports.DeviceManagerRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_device_config_versions._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()).list_device_config_versions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("num_versions", )) + 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 = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = device_manager.ListDeviceConfigVersionsResponse() + # 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 + + pb_return_value = device_manager.ListDeviceConfigVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_device_config_versions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_device_config_versions_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_device_config_versions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("numVersions", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_device_config_versions_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_list_device_config_versions") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_list_device_config_versions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.ListDeviceConfigVersionsRequest.pb(device_manager.ListDeviceConfigVersionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = device_manager.ListDeviceConfigVersionsResponse.to_json(device_manager.ListDeviceConfigVersionsResponse()) + + request = device_manager.ListDeviceConfigVersionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = device_manager.ListDeviceConfigVersionsResponse() + + client.list_device_config_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_device_config_versions_rest_bad_request(transport: str = 'rest', request_type=device_manager.ListDeviceConfigVersionsRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_device_config_versions(request) + + +def test_list_device_config_versions_rest_flattened(): + client = DeviceManagerClient( + 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 = device_manager.ListDeviceConfigVersionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + + # 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 + pb_return_value = device_manager.ListDeviceConfigVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_device_config_versions(**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=projects/*/locations/*/registries/*/devices/*}/configVersions" % client.transport._host, args[1]) + + +def test_list_device_config_versions_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_device_config_versions( + device_manager.ListDeviceConfigVersionsRequest(), + name='name_value', + ) + + +def test_list_device_config_versions_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.ListDeviceStatesRequest, + dict, +]) +def test_list_device_states_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + 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 = device_manager.ListDeviceStatesResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.ListDeviceStatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_device_states(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.ListDeviceStatesResponse) + + +def test_list_device_states_rest_required_fields(request_type=device_manager.ListDeviceStatesRequest): + transport_class = transports.DeviceManagerRestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_device_states._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()).list_device_states._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("num_states", )) + 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 = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = device_manager.ListDeviceStatesResponse() + # 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 + + pb_return_value = device_manager.ListDeviceStatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_device_states(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_device_states_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_device_states._get_unset_required_fields({}) + assert set(unset_fields) == (set(("numStates", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_device_states_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_list_device_states") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_list_device_states") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.ListDeviceStatesRequest.pb(device_manager.ListDeviceStatesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = device_manager.ListDeviceStatesResponse.to_json(device_manager.ListDeviceStatesResponse()) + + request = device_manager.ListDeviceStatesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = device_manager.ListDeviceStatesResponse() + + client.list_device_states(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_device_states_rest_bad_request(transport: str = 'rest', request_type=device_manager.ListDeviceStatesRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_device_states(request) + + +def test_list_device_states_rest_flattened(): + client = DeviceManagerClient( + 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 = device_manager.ListDeviceStatesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + + # 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 + pb_return_value = device_manager.ListDeviceStatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_device_states(**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=projects/*/locations/*/registries/*/devices/*}/states" % client.transport._host, args[1]) + + +def test_list_device_states_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_device_states( + device_manager.ListDeviceStatesRequest(), + name='name_value', + ) + + +def test_list_device_states_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} + 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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # 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 + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_set_iam_policy") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_set_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = DeviceManagerClient( + 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 = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.set_iam_policy(**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/{resource=projects/*/locations/*/registries/*}:setIamPolicy" % client.transport._host, args[1]) + + +def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_set_iam_policy_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} + 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 = policy_pb2.Policy( + version=774, + etag=b'etag_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b'etag_blob' + + +def test_get_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # 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 + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_get_iam_policy") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_get_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = DeviceManagerClient( + 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 = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_iam_policy(**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/{resource=projects/*/locations/*/registries/*}:getIamPolicy" % client.transport._host, args[1]) + + +def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_iam_policy_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} + 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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=['permissions_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ['permissions_value'] + + +def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = 'resource_value' + jsonified_request["permissions"] = 'permissions_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == 'permissions_value' + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # 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 + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_test_iam_permissions") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_test_iam_permissions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = DeviceManagerClient( + 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 = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + resource='resource_value', + permissions=['permissions_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.test_iam_permissions(**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/{resource=projects/*/locations/*/registries/*}:testIamPermissions" % client.transport._host, args[1]) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_test_iam_permissions_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.SendCommandToDeviceRequest, + dict, +]) +def test_send_command_to_device_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + 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 = device_manager.SendCommandToDeviceResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.SendCommandToDeviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.send_command_to_device(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.SendCommandToDeviceResponse) + + +def test_send_command_to_device_rest_required_fields(request_type=device_manager.SendCommandToDeviceRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request_init["name"] = "" + request_init["binary_data"] = b'' + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).send_command_to_device._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' + jsonified_request["binaryData"] = b'binary_data_blob' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).send_command_to_device._get_unset_required_fields(jsonified_request) + 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' + assert "binaryData" in jsonified_request + assert jsonified_request["binaryData"] == b'binary_data_blob' + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = device_manager.SendCommandToDeviceResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = device_manager.SendCommandToDeviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.send_command_to_device(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_send_command_to_device_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.send_command_to_device._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "binaryData", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_send_command_to_device_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_send_command_to_device") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_send_command_to_device") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.SendCommandToDeviceRequest.pb(device_manager.SendCommandToDeviceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = device_manager.SendCommandToDeviceResponse.to_json(device_manager.SendCommandToDeviceResponse()) + + request = device_manager.SendCommandToDeviceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = device_manager.SendCommandToDeviceResponse() + + client.send_command_to_device(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_send_command_to_device_rest_bad_request(transport: str = 'rest', request_type=device_manager.SendCommandToDeviceRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.send_command_to_device(request) + + +def test_send_command_to_device_rest_flattened(): + client = DeviceManagerClient( + 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 = device_manager.SendCommandToDeviceResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + binary_data=b'binary_data_blob', + subfolder='subfolder_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.SendCommandToDeviceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.send_command_to_device(**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=projects/*/locations/*/registries/*/devices/*}:sendCommandToDevice" % client.transport._host, args[1]) + + +def test_send_command_to_device_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + 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.send_command_to_device( + device_manager.SendCommandToDeviceRequest(), + name='name_value', + binary_data=b'binary_data_blob', + subfolder='subfolder_value', + ) + + +def test_send_command_to_device_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.BindDeviceToGatewayRequest, + dict, +]) +def test_bind_device_to_gateway_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + 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 = device_manager.BindDeviceToGatewayResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.BindDeviceToGatewayResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.bind_device_to_gateway(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.BindDeviceToGatewayResponse) + + +def test_bind_device_to_gateway_rest_required_fields(request_type=device_manager.BindDeviceToGatewayRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["gateway_id"] = "" + request_init["device_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bind_device_to_gateway._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["gatewayId"] = 'gateway_id_value' + jsonified_request["deviceId"] = 'device_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bind_device_to_gateway._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "gatewayId" in jsonified_request + assert jsonified_request["gatewayId"] == 'gateway_id_value' + assert "deviceId" in jsonified_request + assert jsonified_request["deviceId"] == 'device_id_value' + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = device_manager.BindDeviceToGatewayResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = device_manager.BindDeviceToGatewayResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.bind_device_to_gateway(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_bind_device_to_gateway_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.bind_device_to_gateway._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "gatewayId", "deviceId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_bind_device_to_gateway_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_bind_device_to_gateway") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_bind_device_to_gateway") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.BindDeviceToGatewayRequest.pb(device_manager.BindDeviceToGatewayRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = device_manager.BindDeviceToGatewayResponse.to_json(device_manager.BindDeviceToGatewayResponse()) + + request = device_manager.BindDeviceToGatewayRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = device_manager.BindDeviceToGatewayResponse() + + client.bind_device_to_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_bind_device_to_gateway_rest_bad_request(transport: str = 'rest', request_type=device_manager.BindDeviceToGatewayRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.bind_device_to_gateway(request) + + +def test_bind_device_to_gateway_rest_flattened(): + client = DeviceManagerClient( + 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 = device_manager.BindDeviceToGatewayResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.BindDeviceToGatewayResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.bind_device_to_gateway(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/registries/*}:bindDeviceToGateway" % client.transport._host, args[1]) + + +def test_bind_device_to_gateway_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + 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.bind_device_to_gateway( + device_manager.BindDeviceToGatewayRequest(), + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + + +def test_bind_device_to_gateway_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + device_manager.UnbindDeviceFromGatewayRequest, + dict, +]) +def test_unbind_device_from_gateway_rest(request_type): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + 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 = device_manager.UnbindDeviceFromGatewayResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.UnbindDeviceFromGatewayResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.unbind_device_from_gateway(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, device_manager.UnbindDeviceFromGatewayResponse) + + +def test_unbind_device_from_gateway_rest_required_fields(request_type=device_manager.UnbindDeviceFromGatewayRequest): + transport_class = transports.DeviceManagerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["gateway_id"] = "" + request_init["device_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).unbind_device_from_gateway._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["gatewayId"] = 'gateway_id_value' + jsonified_request["deviceId"] = 'device_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).unbind_device_from_gateway._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "gatewayId" in jsonified_request + assert jsonified_request["gatewayId"] == 'gateway_id_value' + assert "deviceId" in jsonified_request + assert jsonified_request["deviceId"] == 'device_id_value' + + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = device_manager.UnbindDeviceFromGatewayResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = device_manager.UnbindDeviceFromGatewayResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.unbind_device_from_gateway(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_unbind_device_from_gateway_rest_unset_required_fields(): + transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.unbind_device_from_gateway._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "gatewayId", "deviceId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_unbind_device_from_gateway_rest_interceptors(null_interceptor): + transport = transports.DeviceManagerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), + ) + client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_unbind_device_from_gateway") as post, \ + mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_unbind_device_from_gateway") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = device_manager.UnbindDeviceFromGatewayRequest.pb(device_manager.UnbindDeviceFromGatewayRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = device_manager.UnbindDeviceFromGatewayResponse.to_json(device_manager.UnbindDeviceFromGatewayResponse()) + + request = device_manager.UnbindDeviceFromGatewayRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = device_manager.UnbindDeviceFromGatewayResponse() + + client.unbind_device_from_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_unbind_device_from_gateway_rest_bad_request(transport: str = 'rest', request_type=device_manager.UnbindDeviceFromGatewayRequest): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.unbind_device_from_gateway(request) + + +def test_unbind_device_from_gateway_rest_flattened(): + client = DeviceManagerClient( + 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 = device_manager.UnbindDeviceFromGatewayResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = device_manager.UnbindDeviceFromGatewayResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.unbind_device_from_gateway(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/registries/*}:unbindDeviceFromGateway" % client.transport._host, args[1]) + + +def test_unbind_device_from_gateway_rest_flattened_error(transport: str = 'rest'): + client = DeviceManagerClient( + 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.unbind_device_from_gateway( + device_manager.UnbindDeviceFromGatewayRequest(), + parent='parent_value', + gateway_id='gateway_id_value', + device_id='device_id_value', + ) + + +def test_unbind_device_from_gateway_rest_error(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DeviceManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DeviceManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeviceManagerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DeviceManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DeviceManagerClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DeviceManagerClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DeviceManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeviceManagerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeviceManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DeviceManagerClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeviceManagerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DeviceManagerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DeviceManagerGrpcTransport, + transports.DeviceManagerGrpcAsyncIOTransport, + transports.DeviceManagerRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = DeviceManagerClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DeviceManagerGrpcTransport, + ) + +def test_device_manager_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DeviceManagerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_device_manager_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.iot_v1.services.device_manager.transports.DeviceManagerTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DeviceManagerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_device_registry', + 'get_device_registry', + 'update_device_registry', + 'delete_device_registry', + 'list_device_registries', + 'create_device', + 'get_device', + 'update_device', + 'delete_device', + 'list_devices', + 'modify_cloud_to_device_config', + 'list_device_config_versions', + 'list_device_states', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'send_command_to_device', + 'bind_device_to_gateway', + 'unbind_device_from_gateway', + ) + 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_device_manager_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.cloud.iot_v1.services.device_manager.transports.DeviceManagerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DeviceManagerTransport( + 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', + 'https://www.googleapis.com/auth/cloudiot', +), + quota_project_id="octopus", + ) + + +def test_device_manager_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.cloud.iot_v1.services.device_manager.transports.DeviceManagerTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DeviceManagerTransport() + adc.assert_called_once() + + +def test_device_manager_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) + DeviceManagerClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudiot', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DeviceManagerGrpcTransport, + transports.DeviceManagerGrpcAsyncIOTransport, + ], +) +def test_device_manager_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', 'https://www.googleapis.com/auth/cloudiot',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DeviceManagerGrpcTransport, + transports.DeviceManagerGrpcAsyncIOTransport, + transports.DeviceManagerRestTransport, + ], +) +def test_device_manager_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.DeviceManagerGrpcTransport, grpc_helpers), + (transports.DeviceManagerGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_device_manager_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( + "cloudiot.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudiot', +), + scopes=["1", "2"], + default_host="cloudiot.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DeviceManagerGrpcTransport, transports.DeviceManagerGrpcAsyncIOTransport]) +def test_device_manager_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_device_manager_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.DeviceManagerRestTransport ( + 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_device_manager_host_no_port(transport_name): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudiot.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudiot.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudiot.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_device_manager_host_with_port(transport_name): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudiot.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudiot.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudiot.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_device_manager_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DeviceManagerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DeviceManagerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_device_registry._session + session2 = client2.transport.create_device_registry._session + assert session1 != session2 + session1 = client1.transport.get_device_registry._session + session2 = client2.transport.get_device_registry._session + assert session1 != session2 + session1 = client1.transport.update_device_registry._session + session2 = client2.transport.update_device_registry._session + assert session1 != session2 + session1 = client1.transport.delete_device_registry._session + session2 = client2.transport.delete_device_registry._session + assert session1 != session2 + session1 = client1.transport.list_device_registries._session + session2 = client2.transport.list_device_registries._session + assert session1 != session2 + session1 = client1.transport.create_device._session + session2 = client2.transport.create_device._session + assert session1 != session2 + session1 = client1.transport.get_device._session + session2 = client2.transport.get_device._session + assert session1 != session2 + session1 = client1.transport.update_device._session + session2 = client2.transport.update_device._session + assert session1 != session2 + session1 = client1.transport.delete_device._session + session2 = client2.transport.delete_device._session + assert session1 != session2 + session1 = client1.transport.list_devices._session + session2 = client2.transport.list_devices._session + assert session1 != session2 + session1 = client1.transport.modify_cloud_to_device_config._session + session2 = client2.transport.modify_cloud_to_device_config._session + assert session1 != session2 + session1 = client1.transport.list_device_config_versions._session + session2 = client2.transport.list_device_config_versions._session + assert session1 != session2 + session1 = client1.transport.list_device_states._session + session2 = client2.transport.list_device_states._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + session1 = client1.transport.send_command_to_device._session + session2 = client2.transport.send_command_to_device._session + assert session1 != session2 + session1 = client1.transport.bind_device_to_gateway._session + session2 = client2.transport.bind_device_to_gateway._session + assert session1 != session2 + session1 = client1.transport.unbind_device_from_gateway._session + session2 = client2.transport.unbind_device_from_gateway._session + assert session1 != session2 +def test_device_manager_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DeviceManagerGrpcTransport( + 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_device_manager_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DeviceManagerGrpcAsyncIOTransport( + 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.DeviceManagerGrpcTransport, transports.DeviceManagerGrpcAsyncIOTransport]) +def test_device_manager_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.DeviceManagerGrpcTransport, transports.DeviceManagerGrpcAsyncIOTransport]) +def test_device_manager_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_device_path(): + project = "squid" + location = "clam" + registry = "whelk" + device = "octopus" + expected = "projects/{project}/locations/{location}/registries/{registry}/devices/{device}".format(project=project, location=location, registry=registry, device=device, ) + actual = DeviceManagerClient.device_path(project, location, registry, device) + assert expected == actual + + +def test_parse_device_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "registry": "cuttlefish", + "device": "mussel", + } + path = DeviceManagerClient.device_path(**expected) + + # Check that the path construction is reversible. + actual = DeviceManagerClient.parse_device_path(path) + assert expected == actual + +def test_registry_path(): + project = "winkle" + location = "nautilus" + registry = "scallop" + expected = "projects/{project}/locations/{location}/registries/{registry}".format(project=project, location=location, registry=registry, ) + actual = DeviceManagerClient.registry_path(project, location, registry) + assert expected == actual + + +def test_parse_registry_path(): + expected = { + "project": "abalone", + "location": "squid", + "registry": "clam", + } + path = DeviceManagerClient.registry_path(**expected) + + # Check that the path construction is reversible. + actual = DeviceManagerClient.parse_registry_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DeviceManagerClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = DeviceManagerClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DeviceManagerClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = DeviceManagerClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = DeviceManagerClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DeviceManagerClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DeviceManagerClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = DeviceManagerClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DeviceManagerClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = DeviceManagerClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = DeviceManagerClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DeviceManagerClient.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 = DeviceManagerClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = DeviceManagerClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DeviceManagerClient.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.DeviceManagerTransport, '_prep_wrapped_messages') as prep: + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DeviceManagerTransport, '_prep_wrapped_messages') as prep: + transport_class = DeviceManagerClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DeviceManagerAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DeviceManagerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = DeviceManagerClient( + 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", [ + (DeviceManagerClient, transports.DeviceManagerGrpcTransport), + (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From e5dbc35f732f53f7682a9000cbff20aedf9f8c3a Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 22 Mar 2023 20:18:39 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../services/device_manager/async_client.py | 44 +- .../iot_v1/services/device_manager/client.py | 44 +- owl-bot-staging/v1/.coveragerc | 13 - owl-bot-staging/v1/.flake8 | 33 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 - owl-bot-staging/v1/docs/index.rst | 7 - .../v1/docs/iot_v1/device_manager.rst | 10 - owl-bot-staging/v1/docs/iot_v1/services.rst | 6 - owl-bot-staging/v1/docs/iot_v1/types.rst | 6 - .../v1/google/cloud/iot/__init__.py | 117 - .../v1/google/cloud/iot/gapic_version.py | 16 - owl-bot-staging/v1/google/cloud/iot/py.typed | 2 - .../v1/google/cloud/iot_v1/__init__.py | 118 - .../google/cloud/iot_v1/gapic_metadata.json | 313 - .../v1/google/cloud/iot_v1/gapic_version.py | 16 - .../v1/google/cloud/iot_v1/py.typed | 2 - .../google/cloud/iot_v1/services/__init__.py | 15 - .../services/device_manager/__init__.py | 22 - .../services/device_manager/async_client.py | 2477 ---- .../iot_v1/services/device_manager/client.py | 2617 ---- .../iot_v1/services/device_manager/pagers.py | 261 - .../device_manager/transports/__init__.py | 38 - .../device_manager/transports/base.py | 477 - .../device_manager/transports/grpc.py | 763 -- .../device_manager/transports/grpc_asyncio.py | 762 -- .../device_manager/transports/rest.py | 2535 ---- .../v1/google/cloud/iot_v1/types/__init__.py | 112 - .../cloud/iot_v1/types/device_manager.py | 688 - .../v1/google/cloud/iot_v1/types/resources.py | 868 -- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 184 - ...ce_manager_bind_device_to_gateway_async.py | 54 - ...ice_manager_bind_device_to_gateway_sync.py | 54 - ...ated_device_manager_create_device_async.py | 52 - ...ce_manager_create_device_registry_async.py | 52 - ...ice_manager_create_device_registry_sync.py | 52 - ...rated_device_manager_create_device_sync.py | 52 - ...ated_device_manager_delete_device_async.py | 50 - ...ce_manager_delete_device_registry_async.py | 50 - ...ice_manager_delete_device_registry_sync.py | 50 - ...rated_device_manager_delete_device_sync.py | 50 - ...nerated_device_manager_get_device_async.py | 52 - ...evice_manager_get_device_registry_async.py | 52 - ...device_manager_get_device_registry_sync.py | 52 - ...enerated_device_manager_get_device_sync.py | 52 - ...ted_device_manager_get_iam_policy_async.py | 53 - ...ated_device_manager_get_iam_policy_sync.py | 53 - ...nager_list_device_config_versions_async.py | 52 - ...anager_list_device_config_versions_sync.py | 52 - ...ce_manager_list_device_registries_async.py | 53 - ...ice_manager_list_device_registries_sync.py | 53 - ...device_manager_list_device_states_async.py | 52 - ..._device_manager_list_device_states_sync.py | 52 - ...rated_device_manager_list_devices_async.py | 53 - ...erated_device_manager_list_devices_sync.py | 53 - ...ger_modify_cloud_to_device_config_async.py | 53 - ...ager_modify_cloud_to_device_config_sync.py | 53 - ...ce_manager_send_command_to_device_async.py | 53 - ...ice_manager_send_command_to_device_sync.py | 53 - ...ted_device_manager_set_iam_policy_async.py | 53 - ...ated_device_manager_set_iam_policy_sync.py | 53 - ...vice_manager_test_iam_permissions_async.py | 54 - ...evice_manager_test_iam_permissions_sync.py | 54 - ...anager_unbind_device_from_gateway_async.py | 54 - ...manager_unbind_device_from_gateway_sync.py | 54 - ...ated_device_manager_update_device_async.py | 51 - ...ce_manager_update_device_registry_async.py | 51 - ...ice_manager_update_device_registry_sync.py | 51 - ...rated_device_manager_update_device_sync.py | 51 - .../snippet_metadata_google.cloud.iot.v1.json | 3158 ----- .../v1/scripts/fixup_iot_v1_keywords.py | 194 - owl-bot-staging/v1/setup.py | 91 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.7.txt | 10 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../v1/tests/unit/gapic/iot_v1/__init__.py | 16 - .../unit/gapic/iot_v1/test_device_manager.py | 10954 ---------------- 85 files changed, 38 insertions(+), 29452 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/.flake8 delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/docs/iot_v1/device_manager.rst delete mode 100644 owl-bot-staging/v1/docs/iot_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/iot_v1/types.rst delete mode 100644 owl-bot-staging/v1/google/cloud/iot/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/rest.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/types/device_manager.py delete mode 100644 owl-bot-staging/v1/google/cloud/iot_v1/types/resources.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.iot.v1.json delete mode 100644 owl-bot-staging/v1/scripts/fixup_iot_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/iot_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/iot_v1/test_device_manager.py diff --git a/google/cloud/iot_v1/services/device_manager/async_client.py b/google/cloud/iot_v1/services/device_manager/async_client.py index 032754a8..66fe74b0 100644 --- a/google/cloud/iot_v1/services/device_manager/async_client.py +++ b/google/cloud/iot_v1/services/device_manager/async_client.py @@ -266,7 +266,7 @@ async def sample_create_device_registry(): Args: request (Optional[Union[google.cloud.iot_v1.types.CreateDeviceRegistryRequest, dict]]): - The request object. Request for `CreateDeviceRegistry`. + The request object. Request for ``CreateDeviceRegistry``. parent (:class:`str`): Required. The project and cloud region where this device registry must be created. For example, @@ -377,7 +377,7 @@ async def sample_get_device_registry(): Args: request (Optional[Union[google.cloud.iot_v1.types.GetDeviceRegistryRequest, dict]]): - The request object. Request for `GetDeviceRegistry`. + The request object. Request for ``GetDeviceRegistry``. name (:class:`str`): Required. The name of the device registry. For example, ``projects/example-project/locations/us-central1/registries/my-registry``. @@ -488,7 +488,7 @@ async def sample_update_device_registry(): Args: request (Optional[Union[google.cloud.iot_v1.types.UpdateDeviceRegistryRequest, dict]]): - The request object. Request for `UpdateDeviceRegistry`. + The request object. Request for ``UpdateDeviceRegistry``. device_registry (:class:`google.cloud.iot_v1.types.DeviceRegistry`): Required. The new values for the device registry. The ``id`` field must be empty, and the ``name`` field must @@ -603,7 +603,7 @@ async def sample_delete_device_registry(): Args: request (Optional[Union[google.cloud.iot_v1.types.DeleteDeviceRegistryRequest, dict]]): - The request object. Request for `DeleteDeviceRegistry`. + The request object. Request for ``DeleteDeviceRegistry``. name (:class:`str`): Required. The name of the device registry. For example, ``projects/example-project/locations/us-central1/registries/my-registry``. @@ -708,7 +708,7 @@ async def sample_list_device_registries(): Args: request (Optional[Union[google.cloud.iot_v1.types.ListDeviceRegistriesRequest, dict]]): - The request object. Request for `ListDeviceRegistries`. + The request object. Request for ``ListDeviceRegistries``. parent (:class:`str`): Required. The project and cloud region path. For example, @@ -832,7 +832,7 @@ async def sample_create_device(): Args: request (Optional[Union[google.cloud.iot_v1.types.CreateDeviceRequest, dict]]): - The request object. Request for `CreateDevice`. + The request object. Request for ``CreateDevice``. parent (:class:`str`): Required. The name of the device registry where this device should be created. For example, @@ -943,7 +943,7 @@ async def sample_get_device(): Args: request (Optional[Union[google.cloud.iot_v1.types.GetDeviceRequest, dict]]): - The request object. Request for `GetDevice`. + The request object. Request for ``GetDevice``. name (:class:`str`): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -1054,7 +1054,7 @@ async def sample_update_device(): Args: request (Optional[Union[google.cloud.iot_v1.types.UpdateDeviceRequest, dict]]): - The request object. Request for `UpdateDevice`. + The request object. Request for ``UpdateDevice``. device (:class:`google.cloud.iot_v1.types.Device`): Required. The new values for the device. The ``id`` and ``num_id`` fields must be empty, and the field ``name`` @@ -1167,7 +1167,7 @@ async def sample_delete_device(): Args: request (Optional[Union[google.cloud.iot_v1.types.DeleteDeviceRequest, dict]]): - The request object. Request for `DeleteDevice`. + The request object. Request for ``DeleteDevice``. name (:class:`str`): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -1272,7 +1272,7 @@ async def sample_list_devices(): Args: request (Optional[Union[google.cloud.iot_v1.types.ListDevicesRequest, dict]]): - The request object. Request for `ListDevices`. + The request object. Request for ``ListDevices``. parent (:class:`str`): Required. The device registry path. Required. For example, @@ -1401,8 +1401,7 @@ async def sample_modify_cloud_to_device_config(): Args: request (Optional[Union[google.cloud.iot_v1.types.ModifyCloudToDeviceConfigRequest, dict]]): - The request object. Request for - `ModifyCloudToDeviceConfig`. + The request object. Request for ``ModifyCloudToDeviceConfig``. name (:class:`str`): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -1528,8 +1527,7 @@ async def sample_list_device_config_versions(): Args: request (Optional[Union[google.cloud.iot_v1.types.ListDeviceConfigVersionsRequest, dict]]): - The request object. Request for - `ListDeviceConfigVersions`. + The request object. Request for ``ListDeviceConfigVersions``. name (:class:`str`): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -1641,7 +1639,7 @@ async def sample_list_device_states(): Args: request (Optional[Union[google.cloud.iot_v1.types.ListDeviceStatesRequest, dict]]): - The request object. Request for `ListDeviceStates`. + The request object. Request for ``ListDeviceStates``. name (:class:`str`): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -1754,8 +1752,7 @@ async def sample_set_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being specified. See the @@ -1922,8 +1919,7 @@ async def sample_get_iam_policy(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (:class:`str`): REQUIRED: The resource for which the policy is being requested. See the @@ -2092,8 +2088,7 @@ async def sample_test_iam_permissions(): Args: request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (:class:`str`): REQUIRED: The resource for which the policy detail is being requested. See @@ -2227,7 +2222,7 @@ async def sample_send_command_to_device(): Args: request (Optional[Union[google.cloud.iot_v1.types.SendCommandToDeviceRequest, dict]]): - The request object. Request for `SendCommandToDevice`. + The request object. Request for ``SendCommandToDevice``. name (:class:`str`): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -2372,7 +2367,7 @@ async def sample_bind_device_to_gateway(): Args: request (Optional[Union[google.cloud.iot_v1.types.BindDeviceToGatewayRequest, dict]]): - The request object. Request for `BindDeviceToGateway`. + The request object. Request for ``BindDeviceToGateway``. parent (:class:`str`): Required. The name of the registry. For example, ``projects/example-project/locations/us-central1/registries/my-registry``. @@ -2497,8 +2492,7 @@ async def sample_unbind_device_from_gateway(): Args: request (Optional[Union[google.cloud.iot_v1.types.UnbindDeviceFromGatewayRequest, dict]]): - The request object. Request for - `UnbindDeviceFromGateway`. + The request object. Request for ``UnbindDeviceFromGateway``. parent (:class:`str`): Required. The name of the registry. For example, ``projects/example-project/locations/us-central1/registries/my-registry``. diff --git a/google/cloud/iot_v1/services/device_manager/client.py b/google/cloud/iot_v1/services/device_manager/client.py index 5c9769ff..9922906c 100644 --- a/google/cloud/iot_v1/services/device_manager/client.py +++ b/google/cloud/iot_v1/services/device_manager/client.py @@ -515,7 +515,7 @@ def sample_create_device_registry(): Args: request (Union[google.cloud.iot_v1.types.CreateDeviceRegistryRequest, dict]): - The request object. Request for `CreateDeviceRegistry`. + The request object. Request for ``CreateDeviceRegistry``. parent (str): Required. The project and cloud region where this device registry must be created. For example, @@ -626,7 +626,7 @@ def sample_get_device_registry(): Args: request (Union[google.cloud.iot_v1.types.GetDeviceRegistryRequest, dict]): - The request object. Request for `GetDeviceRegistry`. + The request object. Request for ``GetDeviceRegistry``. name (str): Required. The name of the device registry. For example, ``projects/example-project/locations/us-central1/registries/my-registry``. @@ -727,7 +727,7 @@ def sample_update_device_registry(): Args: request (Union[google.cloud.iot_v1.types.UpdateDeviceRegistryRequest, dict]): - The request object. Request for `UpdateDeviceRegistry`. + The request object. Request for ``UpdateDeviceRegistry``. device_registry (google.cloud.iot_v1.types.DeviceRegistry): Required. The new values for the device registry. The ``id`` field must be empty, and the ``name`` field must @@ -842,7 +842,7 @@ def sample_delete_device_registry(): Args: request (Union[google.cloud.iot_v1.types.DeleteDeviceRegistryRequest, dict]): - The request object. Request for `DeleteDeviceRegistry`. + The request object. Request for ``DeleteDeviceRegistry``. name (str): Required. The name of the device registry. For example, ``projects/example-project/locations/us-central1/registries/my-registry``. @@ -937,7 +937,7 @@ def sample_list_device_registries(): Args: request (Union[google.cloud.iot_v1.types.ListDeviceRegistriesRequest, dict]): - The request object. Request for `ListDeviceRegistries`. + The request object. Request for ``ListDeviceRegistries``. parent (str): Required. The project and cloud region path. For example, @@ -1051,7 +1051,7 @@ def sample_create_device(): Args: request (Union[google.cloud.iot_v1.types.CreateDeviceRequest, dict]): - The request object. Request for `CreateDevice`. + The request object. Request for ``CreateDevice``. parent (str): Required. The name of the device registry where this device should be created. For example, @@ -1162,7 +1162,7 @@ def sample_get_device(): Args: request (Union[google.cloud.iot_v1.types.GetDeviceRequest, dict]): - The request object. Request for `GetDevice`. + The request object. Request for ``GetDevice``. name (str): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -1263,7 +1263,7 @@ def sample_update_device(): Args: request (Union[google.cloud.iot_v1.types.UpdateDeviceRequest, dict]): - The request object. Request for `UpdateDevice`. + The request object. Request for ``UpdateDevice``. device (google.cloud.iot_v1.types.Device): Required. The new values for the device. The ``id`` and ``num_id`` fields must be empty, and the field ``name`` @@ -1376,7 +1376,7 @@ def sample_delete_device(): Args: request (Union[google.cloud.iot_v1.types.DeleteDeviceRequest, dict]): - The request object. Request for `DeleteDevice`. + The request object. Request for ``DeleteDevice``. name (str): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -1471,7 +1471,7 @@ def sample_list_devices(): Args: request (Union[google.cloud.iot_v1.types.ListDevicesRequest, dict]): - The request object. Request for `ListDevices`. + The request object. Request for ``ListDevices``. parent (str): Required. The device registry path. Required. For example, @@ -1590,8 +1590,7 @@ def sample_modify_cloud_to_device_config(): Args: request (Union[google.cloud.iot_v1.types.ModifyCloudToDeviceConfigRequest, dict]): - The request object. Request for - `ModifyCloudToDeviceConfig`. + The request object. Request for ``ModifyCloudToDeviceConfig``. name (str): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -1708,8 +1707,7 @@ def sample_list_device_config_versions(): Args: request (Union[google.cloud.iot_v1.types.ListDeviceConfigVersionsRequest, dict]): - The request object. Request for - `ListDeviceConfigVersions`. + The request object. Request for ``ListDeviceConfigVersions``. name (str): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -1813,7 +1811,7 @@ def sample_list_device_states(): Args: request (Union[google.cloud.iot_v1.types.ListDeviceStatesRequest, dict]): - The request object. Request for `ListDeviceStates`. + The request object. Request for ``ListDeviceStates``. name (str): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -1916,8 +1914,7 @@ def sample_set_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for `SetIamPolicy` - method. + The request object. Request message for ``SetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being specified. See the @@ -2081,8 +2078,7 @@ def sample_get_iam_policy(): Args: request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for `GetIamPolicy` - method. + The request object. Request message for ``GetIamPolicy`` method. resource (str): REQUIRED: The resource for which the policy is being requested. See the @@ -2248,8 +2244,7 @@ def sample_test_iam_permissions(): Args: request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for - `TestIamPermissions` method. + The request object. Request message for ``TestIamPermissions`` method. resource (str): REQUIRED: The resource for which the policy detail is being requested. See @@ -2381,7 +2376,7 @@ def sample_send_command_to_device(): Args: request (Union[google.cloud.iot_v1.types.SendCommandToDeviceRequest, dict]): - The request object. Request for `SendCommandToDevice`. + The request object. Request for ``SendCommandToDevice``. name (str): Required. The name of the device. For example, ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` @@ -2515,7 +2510,7 @@ def sample_bind_device_to_gateway(): Args: request (Union[google.cloud.iot_v1.types.BindDeviceToGatewayRequest, dict]): - The request object. Request for `BindDeviceToGateway`. + The request object. Request for ``BindDeviceToGateway``. parent (str): Required. The name of the registry. For example, ``projects/example-project/locations/us-central1/registries/my-registry``. @@ -2640,8 +2635,7 @@ def sample_unbind_device_from_gateway(): Args: request (Union[google.cloud.iot_v1.types.UnbindDeviceFromGatewayRequest, dict]): - The request object. Request for - `UnbindDeviceFromGateway`. + The request object. Request for ``UnbindDeviceFromGateway``. parent (str): Required. The name of the registry. For example, ``projects/example-project/locations/us-central1/registries/my-registry``. diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 75633d09..00000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/iot/__init__.py - google/cloud/iot/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/v1/.flake8 b/owl-bot-staging/v1/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/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/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index defad235..00000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/iot *.py -recursive-include google/cloud/iot_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 142d2530..00000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Iot 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 Cloud Iot 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/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index d1fe3f41..00000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-iot 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-cloud-iot" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud 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-cloud-iot-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-cloud-iot.tex", - u"google-cloud-iot 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-cloud-iot", - u"Google Cloud Iot 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-cloud-iot", - u"google-cloud-iot Documentation", - author, - "google-cloud-iot", - "GAPIC library for Google Cloud Iot 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/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index c503603d..00000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - iot_v1/services - iot_v1/types diff --git a/owl-bot-staging/v1/docs/iot_v1/device_manager.rst b/owl-bot-staging/v1/docs/iot_v1/device_manager.rst deleted file mode 100644 index bc4660d9..00000000 --- a/owl-bot-staging/v1/docs/iot_v1/device_manager.rst +++ /dev/null @@ -1,10 +0,0 @@ -DeviceManager -------------------------------- - -.. automodule:: google.cloud.iot_v1.services.device_manager - :members: - :inherited-members: - -.. automodule:: google.cloud.iot_v1.services.device_manager.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/iot_v1/services.rst b/owl-bot-staging/v1/docs/iot_v1/services.rst deleted file mode 100644 index 64ed529c..00000000 --- a/owl-bot-staging/v1/docs/iot_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Iot v1 API -==================================== -.. toctree:: - :maxdepth: 2 - - device_manager diff --git a/owl-bot-staging/v1/docs/iot_v1/types.rst b/owl-bot-staging/v1/docs/iot_v1/types.rst deleted file mode 100644 index 94e5a628..00000000 --- a/owl-bot-staging/v1/docs/iot_v1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Iot v1 API -================================= - -.. automodule:: google.cloud.iot_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/iot/__init__.py b/owl-bot-staging/v1/google/cloud/iot/__init__.py deleted file mode 100644 index d8abda36..00000000 --- a/owl-bot-staging/v1/google/cloud/iot/__init__.py +++ /dev/null @@ -1,117 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.iot import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.iot_v1.services.device_manager.client import DeviceManagerClient -from google.cloud.iot_v1.services.device_manager.async_client import DeviceManagerAsyncClient - -from google.cloud.iot_v1.types.device_manager import BindDeviceToGatewayRequest -from google.cloud.iot_v1.types.device_manager import BindDeviceToGatewayResponse -from google.cloud.iot_v1.types.device_manager import CreateDeviceRegistryRequest -from google.cloud.iot_v1.types.device_manager import CreateDeviceRequest -from google.cloud.iot_v1.types.device_manager import DeleteDeviceRegistryRequest -from google.cloud.iot_v1.types.device_manager import DeleteDeviceRequest -from google.cloud.iot_v1.types.device_manager import GatewayListOptions -from google.cloud.iot_v1.types.device_manager import GetDeviceRegistryRequest -from google.cloud.iot_v1.types.device_manager import GetDeviceRequest -from google.cloud.iot_v1.types.device_manager import ListDeviceConfigVersionsRequest -from google.cloud.iot_v1.types.device_manager import ListDeviceConfigVersionsResponse -from google.cloud.iot_v1.types.device_manager import ListDeviceRegistriesRequest -from google.cloud.iot_v1.types.device_manager import ListDeviceRegistriesResponse -from google.cloud.iot_v1.types.device_manager import ListDevicesRequest -from google.cloud.iot_v1.types.device_manager import ListDevicesResponse -from google.cloud.iot_v1.types.device_manager import ListDeviceStatesRequest -from google.cloud.iot_v1.types.device_manager import ListDeviceStatesResponse -from google.cloud.iot_v1.types.device_manager import ModifyCloudToDeviceConfigRequest -from google.cloud.iot_v1.types.device_manager import SendCommandToDeviceRequest -from google.cloud.iot_v1.types.device_manager import SendCommandToDeviceResponse -from google.cloud.iot_v1.types.device_manager import UnbindDeviceFromGatewayRequest -from google.cloud.iot_v1.types.device_manager import UnbindDeviceFromGatewayResponse -from google.cloud.iot_v1.types.device_manager import UpdateDeviceRegistryRequest -from google.cloud.iot_v1.types.device_manager import UpdateDeviceRequest -from google.cloud.iot_v1.types.resources import Device -from google.cloud.iot_v1.types.resources import DeviceConfig -from google.cloud.iot_v1.types.resources import DeviceCredential -from google.cloud.iot_v1.types.resources import DeviceRegistry -from google.cloud.iot_v1.types.resources import DeviceState -from google.cloud.iot_v1.types.resources import EventNotificationConfig -from google.cloud.iot_v1.types.resources import GatewayConfig -from google.cloud.iot_v1.types.resources import HttpConfig -from google.cloud.iot_v1.types.resources import MqttConfig -from google.cloud.iot_v1.types.resources import PublicKeyCertificate -from google.cloud.iot_v1.types.resources import PublicKeyCredential -from google.cloud.iot_v1.types.resources import RegistryCredential -from google.cloud.iot_v1.types.resources import StateNotificationConfig -from google.cloud.iot_v1.types.resources import X509CertificateDetails -from google.cloud.iot_v1.types.resources import GatewayAuthMethod -from google.cloud.iot_v1.types.resources import GatewayType -from google.cloud.iot_v1.types.resources import HttpState -from google.cloud.iot_v1.types.resources import LogLevel -from google.cloud.iot_v1.types.resources import MqttState -from google.cloud.iot_v1.types.resources import PublicKeyCertificateFormat -from google.cloud.iot_v1.types.resources import PublicKeyFormat - -__all__ = ('DeviceManagerClient', - 'DeviceManagerAsyncClient', - 'BindDeviceToGatewayRequest', - 'BindDeviceToGatewayResponse', - 'CreateDeviceRegistryRequest', - 'CreateDeviceRequest', - 'DeleteDeviceRegistryRequest', - 'DeleteDeviceRequest', - 'GatewayListOptions', - 'GetDeviceRegistryRequest', - 'GetDeviceRequest', - 'ListDeviceConfigVersionsRequest', - 'ListDeviceConfigVersionsResponse', - 'ListDeviceRegistriesRequest', - 'ListDeviceRegistriesResponse', - 'ListDevicesRequest', - 'ListDevicesResponse', - 'ListDeviceStatesRequest', - 'ListDeviceStatesResponse', - 'ModifyCloudToDeviceConfigRequest', - 'SendCommandToDeviceRequest', - 'SendCommandToDeviceResponse', - 'UnbindDeviceFromGatewayRequest', - 'UnbindDeviceFromGatewayResponse', - 'UpdateDeviceRegistryRequest', - 'UpdateDeviceRequest', - 'Device', - 'DeviceConfig', - 'DeviceCredential', - 'DeviceRegistry', - 'DeviceState', - 'EventNotificationConfig', - 'GatewayConfig', - 'HttpConfig', - 'MqttConfig', - 'PublicKeyCertificate', - 'PublicKeyCredential', - 'RegistryCredential', - 'StateNotificationConfig', - 'X509CertificateDetails', - 'GatewayAuthMethod', - 'GatewayType', - 'HttpState', - 'LogLevel', - 'MqttState', - 'PublicKeyCertificateFormat', - 'PublicKeyFormat', -) diff --git a/owl-bot-staging/v1/google/cloud/iot/gapic_version.py b/owl-bot-staging/v1/google/cloud/iot/gapic_version.py deleted file mode 100644 index 405b1ceb..00000000 --- a/owl-bot-staging/v1/google/cloud/iot/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/iot/py.typed b/owl-bot-staging/v1/google/cloud/iot/py.typed deleted file mode 100644 index d89d40c8..00000000 --- a/owl-bot-staging/v1/google/cloud/iot/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-iot package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/__init__.py b/owl-bot-staging/v1/google/cloud/iot_v1/__init__.py deleted file mode 100644 index a07ced25..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/__init__.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.iot_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.device_manager import DeviceManagerClient -from .services.device_manager import DeviceManagerAsyncClient - -from .types.device_manager import BindDeviceToGatewayRequest -from .types.device_manager import BindDeviceToGatewayResponse -from .types.device_manager import CreateDeviceRegistryRequest -from .types.device_manager import CreateDeviceRequest -from .types.device_manager import DeleteDeviceRegistryRequest -from .types.device_manager import DeleteDeviceRequest -from .types.device_manager import GatewayListOptions -from .types.device_manager import GetDeviceRegistryRequest -from .types.device_manager import GetDeviceRequest -from .types.device_manager import ListDeviceConfigVersionsRequest -from .types.device_manager import ListDeviceConfigVersionsResponse -from .types.device_manager import ListDeviceRegistriesRequest -from .types.device_manager import ListDeviceRegistriesResponse -from .types.device_manager import ListDevicesRequest -from .types.device_manager import ListDevicesResponse -from .types.device_manager import ListDeviceStatesRequest -from .types.device_manager import ListDeviceStatesResponse -from .types.device_manager import ModifyCloudToDeviceConfigRequest -from .types.device_manager import SendCommandToDeviceRequest -from .types.device_manager import SendCommandToDeviceResponse -from .types.device_manager import UnbindDeviceFromGatewayRequest -from .types.device_manager import UnbindDeviceFromGatewayResponse -from .types.device_manager import UpdateDeviceRegistryRequest -from .types.device_manager import UpdateDeviceRequest -from .types.resources import Device -from .types.resources import DeviceConfig -from .types.resources import DeviceCredential -from .types.resources import DeviceRegistry -from .types.resources import DeviceState -from .types.resources import EventNotificationConfig -from .types.resources import GatewayConfig -from .types.resources import HttpConfig -from .types.resources import MqttConfig -from .types.resources import PublicKeyCertificate -from .types.resources import PublicKeyCredential -from .types.resources import RegistryCredential -from .types.resources import StateNotificationConfig -from .types.resources import X509CertificateDetails -from .types.resources import GatewayAuthMethod -from .types.resources import GatewayType -from .types.resources import HttpState -from .types.resources import LogLevel -from .types.resources import MqttState -from .types.resources import PublicKeyCertificateFormat -from .types.resources import PublicKeyFormat - -__all__ = ( - 'DeviceManagerAsyncClient', -'BindDeviceToGatewayRequest', -'BindDeviceToGatewayResponse', -'CreateDeviceRegistryRequest', -'CreateDeviceRequest', -'DeleteDeviceRegistryRequest', -'DeleteDeviceRequest', -'Device', -'DeviceConfig', -'DeviceCredential', -'DeviceManagerClient', -'DeviceRegistry', -'DeviceState', -'EventNotificationConfig', -'GatewayAuthMethod', -'GatewayConfig', -'GatewayListOptions', -'GatewayType', -'GetDeviceRegistryRequest', -'GetDeviceRequest', -'HttpConfig', -'HttpState', -'ListDeviceConfigVersionsRequest', -'ListDeviceConfigVersionsResponse', -'ListDeviceRegistriesRequest', -'ListDeviceRegistriesResponse', -'ListDeviceStatesRequest', -'ListDeviceStatesResponse', -'ListDevicesRequest', -'ListDevicesResponse', -'LogLevel', -'ModifyCloudToDeviceConfigRequest', -'MqttConfig', -'MqttState', -'PublicKeyCertificate', -'PublicKeyCertificateFormat', -'PublicKeyCredential', -'PublicKeyFormat', -'RegistryCredential', -'SendCommandToDeviceRequest', -'SendCommandToDeviceResponse', -'StateNotificationConfig', -'UnbindDeviceFromGatewayRequest', -'UnbindDeviceFromGatewayResponse', -'UpdateDeviceRegistryRequest', -'UpdateDeviceRequest', -'X509CertificateDetails', -) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/iot_v1/gapic_metadata.json deleted file mode 100644 index b06b7059..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/gapic_metadata.json +++ /dev/null @@ -1,313 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.iot_v1", - "protoPackage": "google.cloud.iot.v1", - "schema": "1.0", - "services": { - "DeviceManager": { - "clients": { - "grpc": { - "libraryClient": "DeviceManagerClient", - "rpcs": { - "BindDeviceToGateway": { - "methods": [ - "bind_device_to_gateway" - ] - }, - "CreateDevice": { - "methods": [ - "create_device" - ] - }, - "CreateDeviceRegistry": { - "methods": [ - "create_device_registry" - ] - }, - "DeleteDevice": { - "methods": [ - "delete_device" - ] - }, - "DeleteDeviceRegistry": { - "methods": [ - "delete_device_registry" - ] - }, - "GetDevice": { - "methods": [ - "get_device" - ] - }, - "GetDeviceRegistry": { - "methods": [ - "get_device_registry" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListDeviceConfigVersions": { - "methods": [ - "list_device_config_versions" - ] - }, - "ListDeviceRegistries": { - "methods": [ - "list_device_registries" - ] - }, - "ListDeviceStates": { - "methods": [ - "list_device_states" - ] - }, - "ListDevices": { - "methods": [ - "list_devices" - ] - }, - "ModifyCloudToDeviceConfig": { - "methods": [ - "modify_cloud_to_device_config" - ] - }, - "SendCommandToDevice": { - "methods": [ - "send_command_to_device" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UnbindDeviceFromGateway": { - "methods": [ - "unbind_device_from_gateway" - ] - }, - "UpdateDevice": { - "methods": [ - "update_device" - ] - }, - "UpdateDeviceRegistry": { - "methods": [ - "update_device_registry" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DeviceManagerAsyncClient", - "rpcs": { - "BindDeviceToGateway": { - "methods": [ - "bind_device_to_gateway" - ] - }, - "CreateDevice": { - "methods": [ - "create_device" - ] - }, - "CreateDeviceRegistry": { - "methods": [ - "create_device_registry" - ] - }, - "DeleteDevice": { - "methods": [ - "delete_device" - ] - }, - "DeleteDeviceRegistry": { - "methods": [ - "delete_device_registry" - ] - }, - "GetDevice": { - "methods": [ - "get_device" - ] - }, - "GetDeviceRegistry": { - "methods": [ - "get_device_registry" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListDeviceConfigVersions": { - "methods": [ - "list_device_config_versions" - ] - }, - "ListDeviceRegistries": { - "methods": [ - "list_device_registries" - ] - }, - "ListDeviceStates": { - "methods": [ - "list_device_states" - ] - }, - "ListDevices": { - "methods": [ - "list_devices" - ] - }, - "ModifyCloudToDeviceConfig": { - "methods": [ - "modify_cloud_to_device_config" - ] - }, - "SendCommandToDevice": { - "methods": [ - "send_command_to_device" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UnbindDeviceFromGateway": { - "methods": [ - "unbind_device_from_gateway" - ] - }, - "UpdateDevice": { - "methods": [ - "update_device" - ] - }, - "UpdateDeviceRegistry": { - "methods": [ - "update_device_registry" - ] - } - } - }, - "rest": { - "libraryClient": "DeviceManagerClient", - "rpcs": { - "BindDeviceToGateway": { - "methods": [ - "bind_device_to_gateway" - ] - }, - "CreateDevice": { - "methods": [ - "create_device" - ] - }, - "CreateDeviceRegistry": { - "methods": [ - "create_device_registry" - ] - }, - "DeleteDevice": { - "methods": [ - "delete_device" - ] - }, - "DeleteDeviceRegistry": { - "methods": [ - "delete_device_registry" - ] - }, - "GetDevice": { - "methods": [ - "get_device" - ] - }, - "GetDeviceRegistry": { - "methods": [ - "get_device_registry" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "ListDeviceConfigVersions": { - "methods": [ - "list_device_config_versions" - ] - }, - "ListDeviceRegistries": { - "methods": [ - "list_device_registries" - ] - }, - "ListDeviceStates": { - "methods": [ - "list_device_states" - ] - }, - "ListDevices": { - "methods": [ - "list_devices" - ] - }, - "ModifyCloudToDeviceConfig": { - "methods": [ - "modify_cloud_to_device_config" - ] - }, - "SendCommandToDevice": { - "methods": [ - "send_command_to_device" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UnbindDeviceFromGateway": { - "methods": [ - "unbind_device_from_gateway" - ] - }, - "UpdateDevice": { - "methods": [ - "update_device" - ] - }, - "UpdateDeviceRegistry": { - "methods": [ - "update_device_registry" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/iot_v1/gapic_version.py deleted file mode 100644 index 405b1ceb..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/py.typed b/owl-bot-staging/v1/google/cloud/iot_v1/py.typed deleted file mode 100644 index d89d40c8..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-iot package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/__init__.py deleted file mode 100644 index e8e1c384..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/__init__.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/__init__.py deleted file mode 100644 index da885f72..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import DeviceManagerClient -from .async_client import DeviceManagerAsyncClient - -__all__ = ( - 'DeviceManagerClient', - 'DeviceManagerAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/async_client.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/async_client.py deleted file mode 100644 index 345b255d..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/async_client.py +++ /dev/null @@ -1,2477 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.iot_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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.iot_v1.services.device_manager import pagers -from google.cloud.iot_v1.types import device_manager -from google.cloud.iot_v1.types import resources -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import DeviceManagerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DeviceManagerGrpcAsyncIOTransport -from .client import DeviceManagerClient - - -class DeviceManagerAsyncClient: - """Internet of Things (IoT) service. Securely connect and manage - IoT devices. - """ - - _client: DeviceManagerClient - - DEFAULT_ENDPOINT = DeviceManagerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DeviceManagerClient.DEFAULT_MTLS_ENDPOINT - - device_path = staticmethod(DeviceManagerClient.device_path) - parse_device_path = staticmethod(DeviceManagerClient.parse_device_path) - registry_path = staticmethod(DeviceManagerClient.registry_path) - parse_registry_path = staticmethod(DeviceManagerClient.parse_registry_path) - common_billing_account_path = staticmethod(DeviceManagerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DeviceManagerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DeviceManagerClient.common_folder_path) - parse_common_folder_path = staticmethod(DeviceManagerClient.parse_common_folder_path) - common_organization_path = staticmethod(DeviceManagerClient.common_organization_path) - parse_common_organization_path = staticmethod(DeviceManagerClient.parse_common_organization_path) - common_project_path = staticmethod(DeviceManagerClient.common_project_path) - parse_common_project_path = staticmethod(DeviceManagerClient.parse_common_project_path) - common_location_path = staticmethod(DeviceManagerClient.common_location_path) - parse_common_location_path = staticmethod(DeviceManagerClient.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: - DeviceManagerAsyncClient: The constructed client. - """ - return DeviceManagerClient.from_service_account_info.__func__(DeviceManagerAsyncClient, 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: - DeviceManagerAsyncClient: The constructed client. - """ - return DeviceManagerClient.from_service_account_file.__func__(DeviceManagerAsyncClient, 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 DeviceManagerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DeviceManagerTransport: - """Returns the transport used by the client instance. - - Returns: - DeviceManagerTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DeviceManagerClient).get_transport_class, type(DeviceManagerClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DeviceManagerTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the device manager client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.DeviceManagerTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = DeviceManagerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_device_registry(self, - request: Optional[Union[device_manager.CreateDeviceRegistryRequest, dict]] = None, - *, - parent: Optional[str] = None, - device_registry: Optional[resources.DeviceRegistry] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DeviceRegistry: - r"""Creates a device registry that contains devices. - - .. 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.cloud import iot_v1 - - async def sample_create_device_registry(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.CreateDeviceRegistryRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_device_registry(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.CreateDeviceRegistryRequest, dict]]): - The request object. Request for ``CreateDeviceRegistry``. - parent (:class:`str`): - Required. The project and cloud region where this device - registry must be created. For example, - ``projects/example-project/locations/us-central1``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - device_registry (:class:`google.cloud.iot_v1.types.DeviceRegistry`): - Required. The device registry. The field ``name`` must - be empty. The server will generate that field from the - device registry ``id`` provided and the ``parent`` - field. - - This corresponds to the ``device_registry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.DeviceRegistry: - A container for a group of devices. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, device_registry]) - 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.") - - request = device_manager.CreateDeviceRegistryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if device_registry is not None: - request.device_registry = device_registry - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_device_registry, - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_device_registry(self, - request: Optional[Union[device_manager.GetDeviceRegistryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DeviceRegistry: - r"""Gets a device registry configuration. - - .. 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.cloud import iot_v1 - - async def sample_get_device_registry(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.GetDeviceRegistryRequest( - name="name_value", - ) - - # Make the request - response = await client.get_device_registry(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.GetDeviceRegistryRequest, dict]]): - The request object. Request for ``GetDeviceRegistry``. - name (:class:`str`): - Required. The name of the device registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.DeviceRegistry: - A container for a group of devices. - """ - # 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.") - - request = device_manager.GetDeviceRegistryRequest(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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_device_registry, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_device_registry(self, - request: Optional[Union[device_manager.UpdateDeviceRegistryRequest, dict]] = None, - *, - device_registry: Optional[resources.DeviceRegistry] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DeviceRegistry: - r"""Updates a device registry configuration. - - .. 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.cloud import iot_v1 - - async def sample_update_device_registry(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.UpdateDeviceRegistryRequest( - ) - - # Make the request - response = await client.update_device_registry(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.UpdateDeviceRegistryRequest, dict]]): - The request object. Request for ``UpdateDeviceRegistry``. - device_registry (:class:`google.cloud.iot_v1.types.DeviceRegistry`): - Required. The new values for the device registry. The - ``id`` field must be empty, and the ``name`` field must - indicate the path of the resource. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``device_registry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Only updates the ``device_registry`` fields - indicated by this mask. The field mask must not be - empty, and it must not contain fields that are immutable - or only set by the server. Mutable top-level fields: - ``event_notification_config``, ``http_config``, - ``mqtt_config``, and ``state_notification_config``. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.DeviceRegistry: - A container for a group of devices. - """ - # 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([device_registry, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = device_manager.UpdateDeviceRegistryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if device_registry is not None: - request.device_registry = device_registry - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_device_registry, - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("device_registry.name", request.device_registry.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_device_registry(self, - request: Optional[Union[device_manager.DeleteDeviceRegistryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a device registry configuration. - - .. 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.cloud import iot_v1 - - async def sample_delete_device_registry(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.DeleteDeviceRegistryRequest( - name="name_value", - ) - - # Make the request - await client.delete_device_registry(request=request) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.DeleteDeviceRegistryRequest, dict]]): - The request object. Request for ``DeleteDeviceRegistry``. - name (:class:`str`): - Required. The name of the device registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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.") - - request = device_manager.DeleteDeviceRegistryRequest(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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_device_registry, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_device_registries(self, - request: Optional[Union[device_manager.ListDeviceRegistriesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDeviceRegistriesAsyncPager: - r"""Lists device registries. - - .. 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.cloud import iot_v1 - - async def sample_list_device_registries(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceRegistriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_device_registries(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.ListDeviceRegistriesRequest, dict]]): - The request object. Request for ``ListDeviceRegistries``. - parent (:class:`str`): - Required. The project and cloud region path. For - example, - ``projects/example-project/locations/us-central1``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.services.device_manager.pagers.ListDeviceRegistriesAsyncPager: - Response for ListDeviceRegistries. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = device_manager.ListDeviceRegistriesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_device_registries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDeviceRegistriesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_device(self, - request: Optional[Union[device_manager.CreateDeviceRequest, dict]] = None, - *, - parent: Optional[str] = None, - device: Optional[resources.Device] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.Device: - r"""Creates a device in a device registry. - - .. 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.cloud import iot_v1 - - async def sample_create_device(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.CreateDeviceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_device(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.CreateDeviceRequest, dict]]): - The request object. Request for ``CreateDevice``. - parent (:class:`str`): - Required. The name of the device registry where this - device should be created. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - device (:class:`google.cloud.iot_v1.types.Device`): - Required. The device registration details. The field - ``name`` must be empty. The server generates ``name`` - from the device registry ``id`` and the ``parent`` - field. - - This corresponds to the ``device`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.Device: - The device resource. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, device]) - 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.") - - request = device_manager.CreateDeviceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if device is not None: - request.device = device - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_device, - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_device(self, - request: Optional[Union[device_manager.GetDeviceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.Device: - r"""Gets details about a device. - - .. 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.cloud import iot_v1 - - async def sample_get_device(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.GetDeviceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_device(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.GetDeviceRequest, dict]]): - The request object. Request for ``GetDevice``. - name (:class:`str`): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.Device: - The device resource. - """ - # 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.") - - request = device_manager.GetDeviceRequest(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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_device, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_device(self, - request: Optional[Union[device_manager.UpdateDeviceRequest, dict]] = None, - *, - device: Optional[resources.Device] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.Device: - r"""Updates a device. - - .. 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.cloud import iot_v1 - - async def sample_update_device(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.UpdateDeviceRequest( - ) - - # Make the request - response = await client.update_device(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.UpdateDeviceRequest, dict]]): - The request object. Request for ``UpdateDevice``. - device (:class:`google.cloud.iot_v1.types.Device`): - Required. The new values for the device. The ``id`` and - ``num_id`` fields must be empty, and the field ``name`` - must specify the name path. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\ or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``device`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Only updates the ``device`` fields indicated - by this mask. The field mask must not be empty, and it - must not contain fields that are immutable or only set - by the server. Mutable top-level fields: - ``credentials``, ``blocked``, and ``metadata`` - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.Device: - The device resource. - """ - # 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([device, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = device_manager.UpdateDeviceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if device is not None: - request.device = device - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_device, - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("device.name", request.device.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_device(self, - request: Optional[Union[device_manager.DeleteDeviceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a device. - - .. 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.cloud import iot_v1 - - async def sample_delete_device(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.DeleteDeviceRequest( - name="name_value", - ) - - # Make the request - await client.delete_device(request=request) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.DeleteDeviceRequest, dict]]): - The request object. Request for ``DeleteDevice``. - name (:class:`str`): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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.") - - request = device_manager.DeleteDeviceRequest(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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_device, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_devices(self, - request: Optional[Union[device_manager.ListDevicesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDevicesAsyncPager: - r"""List devices in a device registry. - - .. 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.cloud import iot_v1 - - async def sample_list_devices(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.ListDevicesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_devices(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.ListDevicesRequest, dict]]): - The request object. Request for ``ListDevices``. - parent (:class:`str`): - Required. The device registry path. Required. For - example, - ``projects/my-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.services.device_manager.pagers.ListDevicesAsyncPager: - Response for ListDevices. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = device_manager.ListDevicesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_devices, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDevicesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def modify_cloud_to_device_config(self, - request: Optional[Union[device_manager.ModifyCloudToDeviceConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - binary_data: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DeviceConfig: - r"""Modifies the configuration for the device, which is - eventually sent from the Cloud IoT Core servers. Returns - the modified configuration version and its metadata. - - .. 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.cloud import iot_v1 - - async def sample_modify_cloud_to_device_config(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.ModifyCloudToDeviceConfigRequest( - name="name_value", - binary_data=b'binary_data_blob', - ) - - # Make the request - response = await client.modify_cloud_to_device_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.ModifyCloudToDeviceConfigRequest, dict]]): - The request object. Request for ``ModifyCloudToDeviceConfig``. - name (:class:`str`): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - binary_data (:class:`bytes`): - Required. The configuration data for - the device. - - This corresponds to the ``binary_data`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.DeviceConfig: - The device configuration. Eventually - delivered to devices. - - """ - # 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, binary_data]) - 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.") - - request = device_manager.ModifyCloudToDeviceConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if binary_data is not None: - request.binary_data = binary_data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.modify_cloud_to_device_config, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ResourceExhausted, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_device_config_versions(self, - request: Optional[Union[device_manager.ListDeviceConfigVersionsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> device_manager.ListDeviceConfigVersionsResponse: - r"""Lists the last few versions of the device - configuration in descending order (i.e.: newest first). - - .. 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.cloud import iot_v1 - - async def sample_list_device_config_versions(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceConfigVersionsRequest( - name="name_value", - ) - - # Make the request - response = await client.list_device_config_versions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.ListDeviceConfigVersionsRequest, dict]]): - The request object. Request for ``ListDeviceConfigVersions``. - name (:class:`str`): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.ListDeviceConfigVersionsResponse: - Response for ListDeviceConfigVersions. - """ - # 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.") - - request = device_manager.ListDeviceConfigVersionsRequest(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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_device_config_versions, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_device_states(self, - request: Optional[Union[device_manager.ListDeviceStatesRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> device_manager.ListDeviceStatesResponse: - r"""Lists the last few versions of the device state in - descending order (i.e.: newest first). - - .. 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.cloud import iot_v1 - - async def sample_list_device_states(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceStatesRequest( - name="name_value", - ) - - # Make the request - response = await client.list_device_states(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.ListDeviceStatesRequest, dict]]): - The request object. Request for ``ListDeviceStates``. - name (:class:`str`): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.ListDeviceStatesResponse: - Response for ListDeviceStates. - """ - # 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.") - - request = device_manager.ListDeviceStatesRequest(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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_device_states, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the access control policy on the specified - resource. Replaces any existing policy. - - .. 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.cloud import iot_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_set_iam_policy(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): - The request object. Request message for ``SetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": [ "user:eve@example.com" ], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **YAML example:** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # 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([resource]) - 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.") - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy for a resource. - Returns an empty policy if the resource exists and does - not have a policy set. - - .. 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.cloud import iot_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_get_iam_policy(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): - The request object. Request message for ``GetIamPolicy`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": [ "user:eve@example.com" ], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **YAML example:** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # 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([resource]) - 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.") - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns permissions that a caller has on the specified resource. - If the resource does not exist, this will return an empty set of - permissions, not a NOT_FOUND error. - - .. 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.cloud import iot_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - async def sample_test_iam_permissions(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): - The request object. Request message for ``TestIamPermissions`` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`MutableSequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # 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([resource, permissions]) - 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.") - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def send_command_to_device(self, - request: Optional[Union[device_manager.SendCommandToDeviceRequest, dict]] = None, - *, - name: Optional[str] = None, - binary_data: Optional[bytes] = None, - subfolder: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> device_manager.SendCommandToDeviceResponse: - r"""Sends a command to the specified device. In order for a device - to be able to receive commands, it must: - - 1) be connected to Cloud IoT Core using the MQTT protocol, and - 2) be subscribed to the group of MQTT topics specified by - /devices/{device-id}/commands/#. This subscription will - receive commands at the top-level topic - /devices/{device-id}/commands as well as commands for - subfolders, like /devices/{device-id}/commands/subfolder. - Note that subscribing to specific subfolders is not - supported. If the command could not be delivered to the - device, this method will return an error; in particular, if - the device is not subscribed, this method will return - FAILED_PRECONDITION. Otherwise, this method will return OK. - If the subscription is QoS 1, at least once delivery will be - guaranteed; for QoS 0, no acknowledgment will be expected - from the device. - - .. 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.cloud import iot_v1 - - async def sample_send_command_to_device(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.SendCommandToDeviceRequest( - name="name_value", - binary_data=b'binary_data_blob', - ) - - # Make the request - response = await client.send_command_to_device(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.SendCommandToDeviceRequest, dict]]): - The request object. Request for ``SendCommandToDevice``. - name (:class:`str`): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - binary_data (:class:`bytes`): - Required. The command data to send to - the device. - - This corresponds to the ``binary_data`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - subfolder (:class:`str`): - Optional subfolder for the command. - If empty, the command will be delivered - to the /devices/{device-id}/commands - topic, otherwise it will be delivered to - the - /devices/{device-id}/commands/{subfolder} - topic. Multi-level subfolders are - allowed. This field must not have more - than 256 characters, and must not - contain any MQTT wildcards ("+" or "#") - or null characters. - - This corresponds to the ``subfolder`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.SendCommandToDeviceResponse: - Response for SendCommandToDevice. - """ - # 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, binary_data, subfolder]) - 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.") - - request = device_manager.SendCommandToDeviceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if binary_data is not None: - request.binary_data = binary_data - if subfolder is not None: - request.subfolder = subfolder - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.send_command_to_device, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ResourceExhausted, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def bind_device_to_gateway(self, - request: Optional[Union[device_manager.BindDeviceToGatewayRequest, dict]] = None, - *, - parent: Optional[str] = None, - gateway_id: Optional[str] = None, - device_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> device_manager.BindDeviceToGatewayResponse: - r"""Associates the device with the gateway. - - .. 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.cloud import iot_v1 - - async def sample_bind_device_to_gateway(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.BindDeviceToGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - device_id="device_id_value", - ) - - # Make the request - response = await client.bind_device_to_gateway(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.BindDeviceToGatewayRequest, dict]]): - The request object. Request for ``BindDeviceToGateway``. - parent (:class:`str`): - Required. The name of the registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - gateway_id (:class:`str`): - Required. The value of ``gateway_id`` can be either the - device numeric ID or the user-defined device identifier. - - This corresponds to the ``gateway_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - device_id (:class:`str`): - Required. The device to associate with the specified - gateway. The value of ``device_id`` can be either the - device numeric ID or the user-defined device identifier. - - This corresponds to the ``device_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.BindDeviceToGatewayResponse: - Response for BindDeviceToGateway. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, gateway_id, device_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = device_manager.BindDeviceToGatewayRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if gateway_id is not None: - request.gateway_id = gateway_id - if device_id is not None: - request.device_id = device_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.bind_device_to_gateway, - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def unbind_device_from_gateway(self, - request: Optional[Union[device_manager.UnbindDeviceFromGatewayRequest, dict]] = None, - *, - parent: Optional[str] = None, - gateway_id: Optional[str] = None, - device_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> device_manager.UnbindDeviceFromGatewayResponse: - r"""Deletes the association between the device and the - gateway. - - .. 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.cloud import iot_v1 - - async def sample_unbind_device_from_gateway(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.UnbindDeviceFromGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - device_id="device_id_value", - ) - - # Make the request - response = await client.unbind_device_from_gateway(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.iot_v1.types.UnbindDeviceFromGatewayRequest, dict]]): - The request object. Request for ``UnbindDeviceFromGateway``. - parent (:class:`str`): - Required. The name of the registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - gateway_id (:class:`str`): - Required. The value of ``gateway_id`` can be either the - device numeric ID or the user-defined device identifier. - - This corresponds to the ``gateway_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - device_id (:class:`str`): - Required. The device to disassociate from the specified - gateway. The value of ``device_id`` can be either the - device numeric ID or the user-defined device identifier. - - This corresponds to the ``device_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.UnbindDeviceFromGatewayResponse: - Response for UnbindDeviceFromGateway. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, gateway_id, device_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = device_manager.UnbindDeviceFromGatewayRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if gateway_id is not None: - request.gateway_id = gateway_id - if device_id is not None: - request.device_id = device_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.unbind_device_from_gateway, - default_timeout=120.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DeviceManagerAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/client.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/client.py deleted file mode 100644 index 94ed7be0..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/client.py +++ /dev/null @@ -1,2617 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.iot_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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.iot_v1.services.device_manager import pagers -from google.cloud.iot_v1.types import device_manager -from google.cloud.iot_v1.types import resources -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import DeviceManagerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DeviceManagerGrpcTransport -from .transports.grpc_asyncio import DeviceManagerGrpcAsyncIOTransport -from .transports.rest import DeviceManagerRestTransport - - -class DeviceManagerClientMeta(type): - """Metaclass for the DeviceManager 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[DeviceManagerTransport]] - _transport_registry["grpc"] = DeviceManagerGrpcTransport - _transport_registry["grpc_asyncio"] = DeviceManagerGrpcAsyncIOTransport - _transport_registry["rest"] = DeviceManagerRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DeviceManagerTransport]: - """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 DeviceManagerClient(metaclass=DeviceManagerClientMeta): - """Internet of Things (IoT) service. Securely connect and manage - IoT devices. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "cloudiot.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DeviceManagerClient: 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: - DeviceManagerClient: 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) -> DeviceManagerTransport: - """Returns the transport used by the client instance. - - Returns: - DeviceManagerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def device_path(project: str,location: str,registry: str,device: str,) -> str: - """Returns a fully-qualified device string.""" - return "projects/{project}/locations/{location}/registries/{registry}/devices/{device}".format(project=project, location=location, registry=registry, device=device, ) - - @staticmethod - def parse_device_path(path: str) -> Dict[str,str]: - """Parses a device path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/registries/(?P.+?)/devices/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def registry_path(project: str,location: str,registry: str,) -> str: - """Returns a fully-qualified registry string.""" - return "projects/{project}/locations/{location}/registries/{registry}".format(project=project, location=location, registry=registry, ) - - @staticmethod - def parse_registry_path(path: str) -> Dict[str,str]: - """Parses a registry path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/registries/(?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): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DeviceManagerTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the device manager client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, DeviceManagerTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DeviceManagerTransport): - # transport is a DeviceManagerTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_device_registry(self, - request: Optional[Union[device_manager.CreateDeviceRegistryRequest, dict]] = None, - *, - parent: Optional[str] = None, - device_registry: Optional[resources.DeviceRegistry] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DeviceRegistry: - r"""Creates a device registry that contains devices. - - .. 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.cloud import iot_v1 - - def sample_create_device_registry(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.CreateDeviceRegistryRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_device_registry(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.CreateDeviceRegistryRequest, dict]): - The request object. Request for ``CreateDeviceRegistry``. - parent (str): - Required. The project and cloud region where this device - registry must be created. For example, - ``projects/example-project/locations/us-central1``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - device_registry (google.cloud.iot_v1.types.DeviceRegistry): - Required. The device registry. The field ``name`` must - be empty. The server will generate that field from the - device registry ``id`` provided and the ``parent`` - field. - - This corresponds to the ``device_registry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.DeviceRegistry: - A container for a group of devices. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, device_registry]) - 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.CreateDeviceRegistryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.CreateDeviceRegistryRequest): - request = device_manager.CreateDeviceRegistryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if device_registry is not None: - request.device_registry = device_registry - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_device_registry] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_device_registry(self, - request: Optional[Union[device_manager.GetDeviceRegistryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DeviceRegistry: - r"""Gets a device registry configuration. - - .. 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.cloud import iot_v1 - - def sample_get_device_registry(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.GetDeviceRegistryRequest( - name="name_value", - ) - - # Make the request - response = client.get_device_registry(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.GetDeviceRegistryRequest, dict]): - The request object. Request for ``GetDeviceRegistry``. - name (str): - Required. The name of the device registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.DeviceRegistry: - A container for a group of devices. - """ - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.GetDeviceRegistryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.GetDeviceRegistryRequest): - request = device_manager.GetDeviceRegistryRequest(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_device_registry] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_device_registry(self, - request: Optional[Union[device_manager.UpdateDeviceRegistryRequest, dict]] = None, - *, - device_registry: Optional[resources.DeviceRegistry] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DeviceRegistry: - r"""Updates a device registry configuration. - - .. 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.cloud import iot_v1 - - def sample_update_device_registry(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.UpdateDeviceRegistryRequest( - ) - - # Make the request - response = client.update_device_registry(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.UpdateDeviceRegistryRequest, dict]): - The request object. Request for ``UpdateDeviceRegistry``. - device_registry (google.cloud.iot_v1.types.DeviceRegistry): - Required. The new values for the device registry. The - ``id`` field must be empty, and the ``name`` field must - indicate the path of the resource. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``device_registry`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Only updates the ``device_registry`` fields - indicated by this mask. The field mask must not be - empty, and it must not contain fields that are immutable - or only set by the server. Mutable top-level fields: - ``event_notification_config``, ``http_config``, - ``mqtt_config``, and ``state_notification_config``. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.DeviceRegistry: - A container for a group of devices. - """ - # 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([device_registry, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.UpdateDeviceRegistryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.UpdateDeviceRegistryRequest): - request = device_manager.UpdateDeviceRegistryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if device_registry is not None: - request.device_registry = device_registry - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_device_registry] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("device_registry.name", request.device_registry.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_device_registry(self, - request: Optional[Union[device_manager.DeleteDeviceRegistryRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a device registry configuration. - - .. 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.cloud import iot_v1 - - def sample_delete_device_registry(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.DeleteDeviceRegistryRequest( - name="name_value", - ) - - # Make the request - client.delete_device_registry(request=request) - - Args: - request (Union[google.cloud.iot_v1.types.DeleteDeviceRegistryRequest, dict]): - The request object. Request for ``DeleteDeviceRegistry``. - name (str): - Required. The name of the device registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.DeleteDeviceRegistryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.DeleteDeviceRegistryRequest): - request = device_manager.DeleteDeviceRegistryRequest(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.delete_device_registry] - - # 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), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_device_registries(self, - request: Optional[Union[device_manager.ListDeviceRegistriesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDeviceRegistriesPager: - r"""Lists device registries. - - .. 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.cloud import iot_v1 - - def sample_list_device_registries(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceRegistriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_device_registries(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.ListDeviceRegistriesRequest, dict]): - The request object. Request for ``ListDeviceRegistries``. - parent (str): - Required. The project and cloud region path. For - example, - ``projects/example-project/locations/us-central1``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.services.device_manager.pagers.ListDeviceRegistriesPager: - Response for ListDeviceRegistries. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.ListDeviceRegistriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.ListDeviceRegistriesRequest): - request = device_manager.ListDeviceRegistriesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_device_registries] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDeviceRegistriesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_device(self, - request: Optional[Union[device_manager.CreateDeviceRequest, dict]] = None, - *, - parent: Optional[str] = None, - device: Optional[resources.Device] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.Device: - r"""Creates a device in a device registry. - - .. 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.cloud import iot_v1 - - def sample_create_device(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.CreateDeviceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_device(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.CreateDeviceRequest, dict]): - The request object. Request for ``CreateDevice``. - parent (str): - Required. The name of the device registry where this - device should be created. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - device (google.cloud.iot_v1.types.Device): - Required. The device registration details. The field - ``name`` must be empty. The server generates ``name`` - from the device registry ``id`` and the ``parent`` - field. - - This corresponds to the ``device`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.Device: - The device resource. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, device]) - 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.CreateDeviceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.CreateDeviceRequest): - request = device_manager.CreateDeviceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if device is not None: - request.device = device - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_device] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_device(self, - request: Optional[Union[device_manager.GetDeviceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.Device: - r"""Gets details about a device. - - .. 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.cloud import iot_v1 - - def sample_get_device(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.GetDeviceRequest( - name="name_value", - ) - - # Make the request - response = client.get_device(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.GetDeviceRequest, dict]): - The request object. Request for ``GetDevice``. - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.Device: - The device resource. - """ - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.GetDeviceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.GetDeviceRequest): - request = device_manager.GetDeviceRequest(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_device] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_device(self, - request: Optional[Union[device_manager.UpdateDeviceRequest, dict]] = None, - *, - device: Optional[resources.Device] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.Device: - r"""Updates a device. - - .. 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.cloud import iot_v1 - - def sample_update_device(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.UpdateDeviceRequest( - ) - - # Make the request - response = client.update_device(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.UpdateDeviceRequest, dict]): - The request object. Request for ``UpdateDevice``. - device (google.cloud.iot_v1.types.Device): - Required. The new values for the device. The ``id`` and - ``num_id`` fields must be empty, and the field ``name`` - must specify the name path. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\ or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``device`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Only updates the ``device`` fields indicated - by this mask. The field mask must not be empty, and it - must not contain fields that are immutable or only set - by the server. Mutable top-level fields: - ``credentials``, ``blocked``, and ``metadata`` - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.Device: - The device resource. - """ - # 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([device, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.UpdateDeviceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.UpdateDeviceRequest): - request = device_manager.UpdateDeviceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if device is not None: - request.device = device - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_device] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("device.name", request.device.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_device(self, - request: Optional[Union[device_manager.DeleteDeviceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a device. - - .. 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.cloud import iot_v1 - - def sample_delete_device(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.DeleteDeviceRequest( - name="name_value", - ) - - # Make the request - client.delete_device(request=request) - - Args: - request (Union[google.cloud.iot_v1.types.DeleteDeviceRequest, dict]): - The request object. Request for ``DeleteDevice``. - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.DeleteDeviceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.DeleteDeviceRequest): - request = device_manager.DeleteDeviceRequest(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.delete_device] - - # 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), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_devices(self, - request: Optional[Union[device_manager.ListDevicesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDevicesPager: - r"""List devices in a device registry. - - .. 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.cloud import iot_v1 - - def sample_list_devices(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.ListDevicesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_devices(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.ListDevicesRequest, dict]): - The request object. Request for ``ListDevices``. - parent (str): - Required. The device registry path. Required. For - example, - ``projects/my-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.services.device_manager.pagers.ListDevicesPager: - Response for ListDevices. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.ListDevicesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.ListDevicesRequest): - request = device_manager.ListDevicesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_devices] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDevicesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def modify_cloud_to_device_config(self, - request: Optional[Union[device_manager.ModifyCloudToDeviceConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - binary_data: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DeviceConfig: - r"""Modifies the configuration for the device, which is - eventually sent from the Cloud IoT Core servers. Returns - the modified configuration version and its metadata. - - .. 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.cloud import iot_v1 - - def sample_modify_cloud_to_device_config(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.ModifyCloudToDeviceConfigRequest( - name="name_value", - binary_data=b'binary_data_blob', - ) - - # Make the request - response = client.modify_cloud_to_device_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.ModifyCloudToDeviceConfigRequest, dict]): - The request object. Request for ``ModifyCloudToDeviceConfig``. - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - binary_data (bytes): - Required. The configuration data for - the device. - - This corresponds to the ``binary_data`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.DeviceConfig: - The device configuration. Eventually - delivered to devices. - - """ - # 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, binary_data]) - 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.ModifyCloudToDeviceConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.ModifyCloudToDeviceConfigRequest): - request = device_manager.ModifyCloudToDeviceConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if binary_data is not None: - request.binary_data = binary_data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.modify_cloud_to_device_config] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_device_config_versions(self, - request: Optional[Union[device_manager.ListDeviceConfigVersionsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> device_manager.ListDeviceConfigVersionsResponse: - r"""Lists the last few versions of the device - configuration in descending order (i.e.: newest first). - - .. 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.cloud import iot_v1 - - def sample_list_device_config_versions(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceConfigVersionsRequest( - name="name_value", - ) - - # Make the request - response = client.list_device_config_versions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.ListDeviceConfigVersionsRequest, dict]): - The request object. Request for ``ListDeviceConfigVersions``. - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.ListDeviceConfigVersionsResponse: - Response for ListDeviceConfigVersions. - """ - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.ListDeviceConfigVersionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.ListDeviceConfigVersionsRequest): - request = device_manager.ListDeviceConfigVersionsRequest(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.list_device_config_versions] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_device_states(self, - request: Optional[Union[device_manager.ListDeviceStatesRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> device_manager.ListDeviceStatesResponse: - r"""Lists the last few versions of the device state in - descending order (i.e.: newest first). - - .. 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.cloud import iot_v1 - - def sample_list_device_states(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceStatesRequest( - name="name_value", - ) - - # Make the request - response = client.list_device_states(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.ListDeviceStatesRequest, dict]): - The request object. Request for ``ListDeviceStates``. - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.ListDeviceStatesResponse: - Response for ListDeviceStates. - """ - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.ListDeviceStatesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.ListDeviceStatesRequest): - request = device_manager.ListDeviceStatesRequest(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.list_device_states] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def set_iam_policy(self, - request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the access control policy on the specified - resource. Replaces any existing policy. - - .. 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.cloud import iot_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_set_iam_policy(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): - The request object. Request message for ``SetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": [ "user:eve@example.com" ], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **YAML example:** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # 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([resource]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_iam_policy(self, - request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, - *, - resource: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy for a resource. - Returns an empty policy if the resource exists and does - not have a policy set. - - .. 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.cloud import iot_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_get_iam_policy(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): - The request object. Request message for ``GetIamPolicy`` method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which specifies access - controls for Google Cloud resources. - - A Policy is a collection of bindings. A binding binds - one or more members, or principals, to a single role. - Principals can be user accounts, service accounts, - Google groups, and domains (such as G Suite). A role - is a named list of permissions; each role can be an - IAM predefined role or a user-created custom role. - - For some types of Google Cloud resources, a binding - can also specify a condition, which is a logical - expression that allows access to a resource only if - the expression evaluates to true. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the [IAM - documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). - - **JSON example:** - - { - "bindings": [ - { - "role": - "roles/resourcemanager.organizationAdmin", - "members": [ "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - - }, { "role": - "roles/resourcemanager.organizationViewer", - "members": [ "user:eve@example.com" ], - "condition": { "title": "expirable access", - "description": "Does not grant access after - Sep 2020", "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", } } - - ], "etag": "BwWWja0YfJA=", "version": 3 - - } - - **YAML example:** - - bindings: - members: - user:\ mike@example.com - - group:\ admins@example.com - domain:google.com - - serviceAccount:\ my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - user:\ eve@example.com role: - roles/resourcemanager.organizationViewer - condition: title: expirable access description: - Does not grant access after Sep 2020 expression: - request.time < - timestamp('2020-10-01T00:00:00.000Z') etag: - BwWWja0YfJA= version: 3 - - For a description of IAM and its features, see the - [IAM - documentation](\ https://cloud.google.com/iam/docs/). - - """ - # 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([resource]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def test_iam_permissions(self, - request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, - *, - resource: Optional[str] = None, - permissions: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns permissions that a caller has on the specified resource. - If the resource does not exist, this will return an empty set of - permissions, not a NOT_FOUND error. - - .. 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.cloud import iot_v1 - from google.iam.v1 import iam_policy_pb2 # type: ignore - - def sample_test_iam_permissions(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): - The request object. Request message for ``TestIamPermissions`` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (MutableSequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # 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([resource, permissions]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def send_command_to_device(self, - request: Optional[Union[device_manager.SendCommandToDeviceRequest, dict]] = None, - *, - name: Optional[str] = None, - binary_data: Optional[bytes] = None, - subfolder: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> device_manager.SendCommandToDeviceResponse: - r"""Sends a command to the specified device. In order for a device - to be able to receive commands, it must: - - 1) be connected to Cloud IoT Core using the MQTT protocol, and - 2) be subscribed to the group of MQTT topics specified by - /devices/{device-id}/commands/#. This subscription will - receive commands at the top-level topic - /devices/{device-id}/commands as well as commands for - subfolders, like /devices/{device-id}/commands/subfolder. - Note that subscribing to specific subfolders is not - supported. If the command could not be delivered to the - device, this method will return an error; in particular, if - the device is not subscribed, this method will return - FAILED_PRECONDITION. Otherwise, this method will return OK. - If the subscription is QoS 1, at least once delivery will be - guaranteed; for QoS 0, no acknowledgment will be expected - from the device. - - .. 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.cloud import iot_v1 - - def sample_send_command_to_device(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.SendCommandToDeviceRequest( - name="name_value", - binary_data=b'binary_data_blob', - ) - - # Make the request - response = client.send_command_to_device(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.SendCommandToDeviceRequest, dict]): - The request object. Request for ``SendCommandToDevice``. - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - binary_data (bytes): - Required. The command data to send to - the device. - - This corresponds to the ``binary_data`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - subfolder (str): - Optional subfolder for the command. - If empty, the command will be delivered - to the /devices/{device-id}/commands - topic, otherwise it will be delivered to - the - /devices/{device-id}/commands/{subfolder} - topic. Multi-level subfolders are - allowed. This field must not have more - than 256 characters, and must not - contain any MQTT wildcards ("+" or "#") - or null characters. - - This corresponds to the ``subfolder`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.SendCommandToDeviceResponse: - Response for SendCommandToDevice. - """ - # 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, binary_data, subfolder]) - 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.SendCommandToDeviceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.SendCommandToDeviceRequest): - request = device_manager.SendCommandToDeviceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if binary_data is not None: - request.binary_data = binary_data - if subfolder is not None: - request.subfolder = subfolder - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.send_command_to_device] - - # 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def bind_device_to_gateway(self, - request: Optional[Union[device_manager.BindDeviceToGatewayRequest, dict]] = None, - *, - parent: Optional[str] = None, - gateway_id: Optional[str] = None, - device_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> device_manager.BindDeviceToGatewayResponse: - r"""Associates the device with the gateway. - - .. 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.cloud import iot_v1 - - def sample_bind_device_to_gateway(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.BindDeviceToGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - device_id="device_id_value", - ) - - # Make the request - response = client.bind_device_to_gateway(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.BindDeviceToGatewayRequest, dict]): - The request object. Request for ``BindDeviceToGateway``. - parent (str): - Required. The name of the registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - gateway_id (str): - Required. The value of ``gateway_id`` can be either the - device numeric ID or the user-defined device identifier. - - This corresponds to the ``gateway_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - device_id (str): - Required. The device to associate with the specified - gateway. The value of ``device_id`` can be either the - device numeric ID or the user-defined device identifier. - - This corresponds to the ``device_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.BindDeviceToGatewayResponse: - Response for BindDeviceToGateway. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, gateway_id, device_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.BindDeviceToGatewayRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.BindDeviceToGatewayRequest): - request = device_manager.BindDeviceToGatewayRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if gateway_id is not None: - request.gateway_id = gateway_id - if device_id is not None: - request.device_id = device_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.bind_device_to_gateway] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def unbind_device_from_gateway(self, - request: Optional[Union[device_manager.UnbindDeviceFromGatewayRequest, dict]] = None, - *, - parent: Optional[str] = None, - gateway_id: Optional[str] = None, - device_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> device_manager.UnbindDeviceFromGatewayResponse: - r"""Deletes the association between the device and the - gateway. - - .. 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.cloud import iot_v1 - - def sample_unbind_device_from_gateway(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.UnbindDeviceFromGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - device_id="device_id_value", - ) - - # Make the request - response = client.unbind_device_from_gateway(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.iot_v1.types.UnbindDeviceFromGatewayRequest, dict]): - The request object. Request for ``UnbindDeviceFromGateway``. - parent (str): - Required. The name of the registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - gateway_id (str): - Required. The value of ``gateway_id`` can be either the - device numeric ID or the user-defined device identifier. - - This corresponds to the ``gateway_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - device_id (str): - Required. The device to disassociate from the specified - gateway. The value of ``device_id`` can be either the - device numeric ID or the user-defined device identifier. - - This corresponds to the ``device_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.iot_v1.types.UnbindDeviceFromGatewayResponse: - Response for UnbindDeviceFromGateway. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, gateway_id, device_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a device_manager.UnbindDeviceFromGatewayRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, device_manager.UnbindDeviceFromGatewayRequest): - request = device_manager.UnbindDeviceFromGatewayRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if gateway_id is not None: - request.gateway_id = gateway_id - if device_id is not None: - request.device_id = device_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.unbind_device_from_gateway] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DeviceManagerClient": - 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__ = ( - "DeviceManagerClient", -) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/pagers.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/pagers.py deleted file mode 100644 index 893c9119..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/pagers.py +++ /dev/null @@ -1,261 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.iot_v1.types import device_manager -from google.cloud.iot_v1.types import resources - - -class ListDeviceRegistriesPager: - """A pager for iterating through ``list_device_registries`` requests. - - This class thinly wraps an initial - :class:`google.cloud.iot_v1.types.ListDeviceRegistriesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``device_registries`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDeviceRegistries`` requests and continue to iterate - through the ``device_registries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.iot_v1.types.ListDeviceRegistriesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., device_manager.ListDeviceRegistriesResponse], - request: device_manager.ListDeviceRegistriesRequest, - response: device_manager.ListDeviceRegistriesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.iot_v1.types.ListDeviceRegistriesRequest): - The initial request object. - response (google.cloud.iot_v1.types.ListDeviceRegistriesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = device_manager.ListDeviceRegistriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[device_manager.ListDeviceRegistriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[resources.DeviceRegistry]: - for page in self.pages: - yield from page.device_registries - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDeviceRegistriesAsyncPager: - """A pager for iterating through ``list_device_registries`` requests. - - This class thinly wraps an initial - :class:`google.cloud.iot_v1.types.ListDeviceRegistriesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``device_registries`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDeviceRegistries`` requests and continue to iterate - through the ``device_registries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.iot_v1.types.ListDeviceRegistriesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[device_manager.ListDeviceRegistriesResponse]], - request: device_manager.ListDeviceRegistriesRequest, - response: device_manager.ListDeviceRegistriesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.iot_v1.types.ListDeviceRegistriesRequest): - The initial request object. - response (google.cloud.iot_v1.types.ListDeviceRegistriesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = device_manager.ListDeviceRegistriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[device_manager.ListDeviceRegistriesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[resources.DeviceRegistry]: - async def async_generator(): - async for page in self.pages: - for response in page.device_registries: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDevicesPager: - """A pager for iterating through ``list_devices`` requests. - - This class thinly wraps an initial - :class:`google.cloud.iot_v1.types.ListDevicesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``devices`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDevices`` requests and continue to iterate - through the ``devices`` field on the - corresponding responses. - - All the usual :class:`google.cloud.iot_v1.types.ListDevicesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., device_manager.ListDevicesResponse], - request: device_manager.ListDevicesRequest, - response: device_manager.ListDevicesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.iot_v1.types.ListDevicesRequest): - The initial request object. - response (google.cloud.iot_v1.types.ListDevicesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = device_manager.ListDevicesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[device_manager.ListDevicesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[resources.Device]: - for page in self.pages: - yield from page.devices - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDevicesAsyncPager: - """A pager for iterating through ``list_devices`` requests. - - This class thinly wraps an initial - :class:`google.cloud.iot_v1.types.ListDevicesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``devices`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDevices`` requests and continue to iterate - through the ``devices`` field on the - corresponding responses. - - All the usual :class:`google.cloud.iot_v1.types.ListDevicesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[device_manager.ListDevicesResponse]], - request: device_manager.ListDevicesRequest, - response: device_manager.ListDevicesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.iot_v1.types.ListDevicesRequest): - The initial request object. - response (google.cloud.iot_v1.types.ListDevicesResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = device_manager.ListDevicesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[device_manager.ListDevicesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[resources.Device]: - async def async_generator(): - async for page in self.pages: - for response in page.devices: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/__init__.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/__init__.py deleted file mode 100644 index b346a3de..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import DeviceManagerTransport -from .grpc import DeviceManagerGrpcTransport -from .grpc_asyncio import DeviceManagerGrpcAsyncIOTransport -from .rest import DeviceManagerRestTransport -from .rest import DeviceManagerRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DeviceManagerTransport]] -_transport_registry['grpc'] = DeviceManagerGrpcTransport -_transport_registry['grpc_asyncio'] = DeviceManagerGrpcAsyncIOTransport -_transport_registry['rest'] = DeviceManagerRestTransport - -__all__ = ( - 'DeviceManagerTransport', - 'DeviceManagerGrpcTransport', - 'DeviceManagerGrpcAsyncIOTransport', - 'DeviceManagerRestTransport', - 'DeviceManagerRestInterceptor', -) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/base.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/base.py deleted file mode 100644 index 98bb5dec..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/base.py +++ /dev/null @@ -1,477 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.iot_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.cloud.iot_v1.types import device_manager -from google.cloud.iot_v1.types import resources -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DeviceManagerTransport(abc.ABC): - """Abstract transport class for DeviceManager.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudiot', - ) - - DEFAULT_HOST: str = 'cloudiot.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_device_registry: gapic_v1.method.wrap_method( - self.create_device_registry, - default_timeout=120.0, - client_info=client_info, - ), - self.get_device_registry: gapic_v1.method.wrap_method( - self.get_device_registry, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.update_device_registry: gapic_v1.method.wrap_method( - self.update_device_registry, - default_timeout=120.0, - client_info=client_info, - ), - self.delete_device_registry: gapic_v1.method.wrap_method( - self.delete_device_registry, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.list_device_registries: gapic_v1.method.wrap_method( - self.list_device_registries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.create_device: gapic_v1.method.wrap_method( - self.create_device, - default_timeout=120.0, - client_info=client_info, - ), - self.get_device: gapic_v1.method.wrap_method( - self.get_device, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.update_device: gapic_v1.method.wrap_method( - self.update_device, - default_timeout=120.0, - client_info=client_info, - ), - self.delete_device: gapic_v1.method.wrap_method( - self.delete_device, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.list_devices: gapic_v1.method.wrap_method( - self.list_devices, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.modify_cloud_to_device_config: gapic_v1.method.wrap_method( - self.modify_cloud_to_device_config, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ResourceExhausted, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.list_device_config_versions: gapic_v1.method.wrap_method( - self.list_device_config_versions, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.list_device_states: gapic_v1.method.wrap_method( - self.list_device_states, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=120.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=120.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=120.0, - client_info=client_info, - ), - self.send_command_to_device: gapic_v1.method.wrap_method( - self.send_command_to_device, - default_retry=retries.Retry( -initial=1.0,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ResourceExhausted, - core_exceptions.ServiceUnavailable, - ), - deadline=120.0, - ), - default_timeout=120.0, - client_info=client_info, - ), - self.bind_device_to_gateway: gapic_v1.method.wrap_method( - self.bind_device_to_gateway, - default_timeout=120.0, - client_info=client_info, - ), - self.unbind_device_from_gateway: gapic_v1.method.wrap_method( - self.unbind_device_from_gateway, - default_timeout=120.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def create_device_registry(self) -> Callable[ - [device_manager.CreateDeviceRegistryRequest], - Union[ - resources.DeviceRegistry, - Awaitable[resources.DeviceRegistry] - ]]: - raise NotImplementedError() - - @property - def get_device_registry(self) -> Callable[ - [device_manager.GetDeviceRegistryRequest], - Union[ - resources.DeviceRegistry, - Awaitable[resources.DeviceRegistry] - ]]: - raise NotImplementedError() - - @property - def update_device_registry(self) -> Callable[ - [device_manager.UpdateDeviceRegistryRequest], - Union[ - resources.DeviceRegistry, - Awaitable[resources.DeviceRegistry] - ]]: - raise NotImplementedError() - - @property - def delete_device_registry(self) -> Callable[ - [device_manager.DeleteDeviceRegistryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_device_registries(self) -> Callable[ - [device_manager.ListDeviceRegistriesRequest], - Union[ - device_manager.ListDeviceRegistriesResponse, - Awaitable[device_manager.ListDeviceRegistriesResponse] - ]]: - raise NotImplementedError() - - @property - def create_device(self) -> Callable[ - [device_manager.CreateDeviceRequest], - Union[ - resources.Device, - Awaitable[resources.Device] - ]]: - raise NotImplementedError() - - @property - def get_device(self) -> Callable[ - [device_manager.GetDeviceRequest], - Union[ - resources.Device, - Awaitable[resources.Device] - ]]: - raise NotImplementedError() - - @property - def update_device(self) -> Callable[ - [device_manager.UpdateDeviceRequest], - Union[ - resources.Device, - Awaitable[resources.Device] - ]]: - raise NotImplementedError() - - @property - def delete_device(self) -> Callable[ - [device_manager.DeleteDeviceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_devices(self) -> Callable[ - [device_manager.ListDevicesRequest], - Union[ - device_manager.ListDevicesResponse, - Awaitable[device_manager.ListDevicesResponse] - ]]: - raise NotImplementedError() - - @property - def modify_cloud_to_device_config(self) -> Callable[ - [device_manager.ModifyCloudToDeviceConfigRequest], - Union[ - resources.DeviceConfig, - Awaitable[resources.DeviceConfig] - ]]: - raise NotImplementedError() - - @property - def list_device_config_versions(self) -> Callable[ - [device_manager.ListDeviceConfigVersionsRequest], - Union[ - device_manager.ListDeviceConfigVersionsResponse, - Awaitable[device_manager.ListDeviceConfigVersionsResponse] - ]]: - raise NotImplementedError() - - @property - def list_device_states(self) -> Callable[ - [device_manager.ListDeviceStatesRequest], - Union[ - device_manager.ListDeviceStatesResponse, - Awaitable[device_manager.ListDeviceStatesResponse] - ]]: - raise NotImplementedError() - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[ - policy_pb2.Policy, - Awaitable[policy_pb2.Policy] - ]]: - raise NotImplementedError() - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def send_command_to_device(self) -> Callable[ - [device_manager.SendCommandToDeviceRequest], - Union[ - device_manager.SendCommandToDeviceResponse, - Awaitable[device_manager.SendCommandToDeviceResponse] - ]]: - raise NotImplementedError() - - @property - def bind_device_to_gateway(self) -> Callable[ - [device_manager.BindDeviceToGatewayRequest], - Union[ - device_manager.BindDeviceToGatewayResponse, - Awaitable[device_manager.BindDeviceToGatewayResponse] - ]]: - raise NotImplementedError() - - @property - def unbind_device_from_gateway(self) -> Callable[ - [device_manager.UnbindDeviceFromGatewayRequest], - Union[ - device_manager.UnbindDeviceFromGatewayResponse, - Awaitable[device_manager.UnbindDeviceFromGatewayResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DeviceManagerTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc.py deleted file mode 100644 index 895558d8..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc.py +++ /dev/null @@ -1,763 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.iot_v1.types import device_manager -from google.cloud.iot_v1.types import resources -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DeviceManagerTransport, DEFAULT_CLIENT_INFO - - -class DeviceManagerGrpcTransport(DeviceManagerTransport): - """gRPC backend transport for DeviceManager. - - Internet of Things (IoT) service. Securely connect and manage - IoT devices. - - 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 = 'cloudiot.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudiot.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def create_device_registry(self) -> Callable[ - [device_manager.CreateDeviceRegistryRequest], - resources.DeviceRegistry]: - r"""Return a callable for the create device registry method over gRPC. - - Creates a device registry that contains devices. - - Returns: - Callable[[~.CreateDeviceRegistryRequest], - ~.DeviceRegistry]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_device_registry' not in self._stubs: - self._stubs['create_device_registry'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/CreateDeviceRegistry', - request_serializer=device_manager.CreateDeviceRegistryRequest.serialize, - response_deserializer=resources.DeviceRegistry.deserialize, - ) - return self._stubs['create_device_registry'] - - @property - def get_device_registry(self) -> Callable[ - [device_manager.GetDeviceRegistryRequest], - resources.DeviceRegistry]: - r"""Return a callable for the get device registry method over gRPC. - - Gets a device registry configuration. - - Returns: - Callable[[~.GetDeviceRegistryRequest], - ~.DeviceRegistry]: - 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_device_registry' not in self._stubs: - self._stubs['get_device_registry'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/GetDeviceRegistry', - request_serializer=device_manager.GetDeviceRegistryRequest.serialize, - response_deserializer=resources.DeviceRegistry.deserialize, - ) - return self._stubs['get_device_registry'] - - @property - def update_device_registry(self) -> Callable[ - [device_manager.UpdateDeviceRegistryRequest], - resources.DeviceRegistry]: - r"""Return a callable for the update device registry method over gRPC. - - Updates a device registry configuration. - - Returns: - Callable[[~.UpdateDeviceRegistryRequest], - ~.DeviceRegistry]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_device_registry' not in self._stubs: - self._stubs['update_device_registry'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/UpdateDeviceRegistry', - request_serializer=device_manager.UpdateDeviceRegistryRequest.serialize, - response_deserializer=resources.DeviceRegistry.deserialize, - ) - return self._stubs['update_device_registry'] - - @property - def delete_device_registry(self) -> Callable[ - [device_manager.DeleteDeviceRegistryRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete device registry method over gRPC. - - Deletes a device registry configuration. - - Returns: - Callable[[~.DeleteDeviceRegistryRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_device_registry' not in self._stubs: - self._stubs['delete_device_registry'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/DeleteDeviceRegistry', - request_serializer=device_manager.DeleteDeviceRegistryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_device_registry'] - - @property - def list_device_registries(self) -> Callable[ - [device_manager.ListDeviceRegistriesRequest], - device_manager.ListDeviceRegistriesResponse]: - r"""Return a callable for the list device registries method over gRPC. - - Lists device registries. - - Returns: - Callable[[~.ListDeviceRegistriesRequest], - ~.ListDeviceRegistriesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_device_registries' not in self._stubs: - self._stubs['list_device_registries'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/ListDeviceRegistries', - request_serializer=device_manager.ListDeviceRegistriesRequest.serialize, - response_deserializer=device_manager.ListDeviceRegistriesResponse.deserialize, - ) - return self._stubs['list_device_registries'] - - @property - def create_device(self) -> Callable[ - [device_manager.CreateDeviceRequest], - resources.Device]: - r"""Return a callable for the create device method over gRPC. - - Creates a device in a device registry. - - Returns: - Callable[[~.CreateDeviceRequest], - ~.Device]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_device' not in self._stubs: - self._stubs['create_device'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/CreateDevice', - request_serializer=device_manager.CreateDeviceRequest.serialize, - response_deserializer=resources.Device.deserialize, - ) - return self._stubs['create_device'] - - @property - def get_device(self) -> Callable[ - [device_manager.GetDeviceRequest], - resources.Device]: - r"""Return a callable for the get device method over gRPC. - - Gets details about a device. - - Returns: - Callable[[~.GetDeviceRequest], - ~.Device]: - 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_device' not in self._stubs: - self._stubs['get_device'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/GetDevice', - request_serializer=device_manager.GetDeviceRequest.serialize, - response_deserializer=resources.Device.deserialize, - ) - return self._stubs['get_device'] - - @property - def update_device(self) -> Callable[ - [device_manager.UpdateDeviceRequest], - resources.Device]: - r"""Return a callable for the update device method over gRPC. - - Updates a device. - - Returns: - Callable[[~.UpdateDeviceRequest], - ~.Device]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_device' not in self._stubs: - self._stubs['update_device'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/UpdateDevice', - request_serializer=device_manager.UpdateDeviceRequest.serialize, - response_deserializer=resources.Device.deserialize, - ) - return self._stubs['update_device'] - - @property - def delete_device(self) -> Callable[ - [device_manager.DeleteDeviceRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete device method over gRPC. - - Deletes a device. - - Returns: - Callable[[~.DeleteDeviceRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_device' not in self._stubs: - self._stubs['delete_device'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/DeleteDevice', - request_serializer=device_manager.DeleteDeviceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_device'] - - @property - def list_devices(self) -> Callable[ - [device_manager.ListDevicesRequest], - device_manager.ListDevicesResponse]: - r"""Return a callable for the list devices method over gRPC. - - List devices in a device registry. - - Returns: - Callable[[~.ListDevicesRequest], - ~.ListDevicesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_devices' not in self._stubs: - self._stubs['list_devices'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/ListDevices', - request_serializer=device_manager.ListDevicesRequest.serialize, - response_deserializer=device_manager.ListDevicesResponse.deserialize, - ) - return self._stubs['list_devices'] - - @property - def modify_cloud_to_device_config(self) -> Callable[ - [device_manager.ModifyCloudToDeviceConfigRequest], - resources.DeviceConfig]: - r"""Return a callable for the modify cloud to device config method over gRPC. - - Modifies the configuration for the device, which is - eventually sent from the Cloud IoT Core servers. Returns - the modified configuration version and its metadata. - - Returns: - Callable[[~.ModifyCloudToDeviceConfigRequest], - ~.DeviceConfig]: - 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 'modify_cloud_to_device_config' not in self._stubs: - self._stubs['modify_cloud_to_device_config'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/ModifyCloudToDeviceConfig', - request_serializer=device_manager.ModifyCloudToDeviceConfigRequest.serialize, - response_deserializer=resources.DeviceConfig.deserialize, - ) - return self._stubs['modify_cloud_to_device_config'] - - @property - def list_device_config_versions(self) -> Callable[ - [device_manager.ListDeviceConfigVersionsRequest], - device_manager.ListDeviceConfigVersionsResponse]: - r"""Return a callable for the list device config versions method over gRPC. - - Lists the last few versions of the device - configuration in descending order (i.e.: newest first). - - Returns: - Callable[[~.ListDeviceConfigVersionsRequest], - ~.ListDeviceConfigVersionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_device_config_versions' not in self._stubs: - self._stubs['list_device_config_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/ListDeviceConfigVersions', - request_serializer=device_manager.ListDeviceConfigVersionsRequest.serialize, - response_deserializer=device_manager.ListDeviceConfigVersionsResponse.deserialize, - ) - return self._stubs['list_device_config_versions'] - - @property - def list_device_states(self) -> Callable[ - [device_manager.ListDeviceStatesRequest], - device_manager.ListDeviceStatesResponse]: - r"""Return a callable for the list device states method over gRPC. - - Lists the last few versions of the device state in - descending order (i.e.: newest first). - - Returns: - Callable[[~.ListDeviceStatesRequest], - ~.ListDeviceStatesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_device_states' not in self._stubs: - self._stubs['list_device_states'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/ListDeviceStates', - request_serializer=device_manager.ListDeviceStatesRequest.serialize, - response_deserializer=device_manager.ListDeviceStatesResponse.deserialize, - ) - return self._stubs['list_device_states'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - resource. Replaces any existing policy. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - 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 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy for a resource. - Returns an empty policy if the resource exists and does - not have a policy set. - - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - 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_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns permissions that a caller has on the specified resource. - If the resource does not exist, this will return an empty set of - permissions, not a NOT_FOUND error. - - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - 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 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def send_command_to_device(self) -> Callable[ - [device_manager.SendCommandToDeviceRequest], - device_manager.SendCommandToDeviceResponse]: - r"""Return a callable for the send command to device method over gRPC. - - Sends a command to the specified device. In order for a device - to be able to receive commands, it must: - - 1) be connected to Cloud IoT Core using the MQTT protocol, and - 2) be subscribed to the group of MQTT topics specified by - /devices/{device-id}/commands/#. This subscription will - receive commands at the top-level topic - /devices/{device-id}/commands as well as commands for - subfolders, like /devices/{device-id}/commands/subfolder. - Note that subscribing to specific subfolders is not - supported. If the command could not be delivered to the - device, this method will return an error; in particular, if - the device is not subscribed, this method will return - FAILED_PRECONDITION. Otherwise, this method will return OK. - If the subscription is QoS 1, at least once delivery will be - guaranteed; for QoS 0, no acknowledgment will be expected - from the device. - - Returns: - Callable[[~.SendCommandToDeviceRequest], - ~.SendCommandToDeviceResponse]: - 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 'send_command_to_device' not in self._stubs: - self._stubs['send_command_to_device'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/SendCommandToDevice', - request_serializer=device_manager.SendCommandToDeviceRequest.serialize, - response_deserializer=device_manager.SendCommandToDeviceResponse.deserialize, - ) - return self._stubs['send_command_to_device'] - - @property - def bind_device_to_gateway(self) -> Callable[ - [device_manager.BindDeviceToGatewayRequest], - device_manager.BindDeviceToGatewayResponse]: - r"""Return a callable for the bind device to gateway method over gRPC. - - Associates the device with the gateway. - - Returns: - Callable[[~.BindDeviceToGatewayRequest], - ~.BindDeviceToGatewayResponse]: - 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 'bind_device_to_gateway' not in self._stubs: - self._stubs['bind_device_to_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/BindDeviceToGateway', - request_serializer=device_manager.BindDeviceToGatewayRequest.serialize, - response_deserializer=device_manager.BindDeviceToGatewayResponse.deserialize, - ) - return self._stubs['bind_device_to_gateway'] - - @property - def unbind_device_from_gateway(self) -> Callable[ - [device_manager.UnbindDeviceFromGatewayRequest], - device_manager.UnbindDeviceFromGatewayResponse]: - r"""Return a callable for the unbind device from gateway method over gRPC. - - Deletes the association between the device and the - gateway. - - Returns: - Callable[[~.UnbindDeviceFromGatewayRequest], - ~.UnbindDeviceFromGatewayResponse]: - 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 'unbind_device_from_gateway' not in self._stubs: - self._stubs['unbind_device_from_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/UnbindDeviceFromGateway', - request_serializer=device_manager.UnbindDeviceFromGatewayRequest.serialize, - response_deserializer=device_manager.UnbindDeviceFromGatewayResponse.deserialize, - ) - return self._stubs['unbind_device_from_gateway'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DeviceManagerGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc_asyncio.py deleted file mode 100644 index 167d9a7c..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/grpc_asyncio.py +++ /dev/null @@ -1,762 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.iot_v1.types import device_manager -from google.cloud.iot_v1.types import resources -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DeviceManagerTransport, DEFAULT_CLIENT_INFO -from .grpc import DeviceManagerGrpcTransport - - -class DeviceManagerGrpcAsyncIOTransport(DeviceManagerTransport): - """gRPC AsyncIO backend transport for DeviceManager. - - Internet of Things (IoT) service. Securely connect and manage - IoT devices. - - 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 = 'cloudiot.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'cloudiot.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def create_device_registry(self) -> Callable[ - [device_manager.CreateDeviceRegistryRequest], - Awaitable[resources.DeviceRegistry]]: - r"""Return a callable for the create device registry method over gRPC. - - Creates a device registry that contains devices. - - Returns: - Callable[[~.CreateDeviceRegistryRequest], - Awaitable[~.DeviceRegistry]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_device_registry' not in self._stubs: - self._stubs['create_device_registry'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/CreateDeviceRegistry', - request_serializer=device_manager.CreateDeviceRegistryRequest.serialize, - response_deserializer=resources.DeviceRegistry.deserialize, - ) - return self._stubs['create_device_registry'] - - @property - def get_device_registry(self) -> Callable[ - [device_manager.GetDeviceRegistryRequest], - Awaitable[resources.DeviceRegistry]]: - r"""Return a callable for the get device registry method over gRPC. - - Gets a device registry configuration. - - Returns: - Callable[[~.GetDeviceRegistryRequest], - Awaitable[~.DeviceRegistry]]: - 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_device_registry' not in self._stubs: - self._stubs['get_device_registry'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/GetDeviceRegistry', - request_serializer=device_manager.GetDeviceRegistryRequest.serialize, - response_deserializer=resources.DeviceRegistry.deserialize, - ) - return self._stubs['get_device_registry'] - - @property - def update_device_registry(self) -> Callable[ - [device_manager.UpdateDeviceRegistryRequest], - Awaitable[resources.DeviceRegistry]]: - r"""Return a callable for the update device registry method over gRPC. - - Updates a device registry configuration. - - Returns: - Callable[[~.UpdateDeviceRegistryRequest], - Awaitable[~.DeviceRegistry]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_device_registry' not in self._stubs: - self._stubs['update_device_registry'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/UpdateDeviceRegistry', - request_serializer=device_manager.UpdateDeviceRegistryRequest.serialize, - response_deserializer=resources.DeviceRegistry.deserialize, - ) - return self._stubs['update_device_registry'] - - @property - def delete_device_registry(self) -> Callable[ - [device_manager.DeleteDeviceRegistryRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete device registry method over gRPC. - - Deletes a device registry configuration. - - Returns: - Callable[[~.DeleteDeviceRegistryRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_device_registry' not in self._stubs: - self._stubs['delete_device_registry'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/DeleteDeviceRegistry', - request_serializer=device_manager.DeleteDeviceRegistryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_device_registry'] - - @property - def list_device_registries(self) -> Callable[ - [device_manager.ListDeviceRegistriesRequest], - Awaitable[device_manager.ListDeviceRegistriesResponse]]: - r"""Return a callable for the list device registries method over gRPC. - - Lists device registries. - - Returns: - Callable[[~.ListDeviceRegistriesRequest], - Awaitable[~.ListDeviceRegistriesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_device_registries' not in self._stubs: - self._stubs['list_device_registries'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/ListDeviceRegistries', - request_serializer=device_manager.ListDeviceRegistriesRequest.serialize, - response_deserializer=device_manager.ListDeviceRegistriesResponse.deserialize, - ) - return self._stubs['list_device_registries'] - - @property - def create_device(self) -> Callable[ - [device_manager.CreateDeviceRequest], - Awaitable[resources.Device]]: - r"""Return a callable for the create device method over gRPC. - - Creates a device in a device registry. - - Returns: - Callable[[~.CreateDeviceRequest], - Awaitable[~.Device]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_device' not in self._stubs: - self._stubs['create_device'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/CreateDevice', - request_serializer=device_manager.CreateDeviceRequest.serialize, - response_deserializer=resources.Device.deserialize, - ) - return self._stubs['create_device'] - - @property - def get_device(self) -> Callable[ - [device_manager.GetDeviceRequest], - Awaitable[resources.Device]]: - r"""Return a callable for the get device method over gRPC. - - Gets details about a device. - - Returns: - Callable[[~.GetDeviceRequest], - Awaitable[~.Device]]: - 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_device' not in self._stubs: - self._stubs['get_device'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/GetDevice', - request_serializer=device_manager.GetDeviceRequest.serialize, - response_deserializer=resources.Device.deserialize, - ) - return self._stubs['get_device'] - - @property - def update_device(self) -> Callable[ - [device_manager.UpdateDeviceRequest], - Awaitable[resources.Device]]: - r"""Return a callable for the update device method over gRPC. - - Updates a device. - - Returns: - Callable[[~.UpdateDeviceRequest], - Awaitable[~.Device]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_device' not in self._stubs: - self._stubs['update_device'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/UpdateDevice', - request_serializer=device_manager.UpdateDeviceRequest.serialize, - response_deserializer=resources.Device.deserialize, - ) - return self._stubs['update_device'] - - @property - def delete_device(self) -> Callable[ - [device_manager.DeleteDeviceRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete device method over gRPC. - - Deletes a device. - - Returns: - Callable[[~.DeleteDeviceRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_device' not in self._stubs: - self._stubs['delete_device'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/DeleteDevice', - request_serializer=device_manager.DeleteDeviceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_device'] - - @property - def list_devices(self) -> Callable[ - [device_manager.ListDevicesRequest], - Awaitable[device_manager.ListDevicesResponse]]: - r"""Return a callable for the list devices method over gRPC. - - List devices in a device registry. - - Returns: - Callable[[~.ListDevicesRequest], - Awaitable[~.ListDevicesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_devices' not in self._stubs: - self._stubs['list_devices'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/ListDevices', - request_serializer=device_manager.ListDevicesRequest.serialize, - response_deserializer=device_manager.ListDevicesResponse.deserialize, - ) - return self._stubs['list_devices'] - - @property - def modify_cloud_to_device_config(self) -> Callable[ - [device_manager.ModifyCloudToDeviceConfigRequest], - Awaitable[resources.DeviceConfig]]: - r"""Return a callable for the modify cloud to device config method over gRPC. - - Modifies the configuration for the device, which is - eventually sent from the Cloud IoT Core servers. Returns - the modified configuration version and its metadata. - - Returns: - Callable[[~.ModifyCloudToDeviceConfigRequest], - Awaitable[~.DeviceConfig]]: - 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 'modify_cloud_to_device_config' not in self._stubs: - self._stubs['modify_cloud_to_device_config'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/ModifyCloudToDeviceConfig', - request_serializer=device_manager.ModifyCloudToDeviceConfigRequest.serialize, - response_deserializer=resources.DeviceConfig.deserialize, - ) - return self._stubs['modify_cloud_to_device_config'] - - @property - def list_device_config_versions(self) -> Callable[ - [device_manager.ListDeviceConfigVersionsRequest], - Awaitable[device_manager.ListDeviceConfigVersionsResponse]]: - r"""Return a callable for the list device config versions method over gRPC. - - Lists the last few versions of the device - configuration in descending order (i.e.: newest first). - - Returns: - Callable[[~.ListDeviceConfigVersionsRequest], - Awaitable[~.ListDeviceConfigVersionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_device_config_versions' not in self._stubs: - self._stubs['list_device_config_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/ListDeviceConfigVersions', - request_serializer=device_manager.ListDeviceConfigVersionsRequest.serialize, - response_deserializer=device_manager.ListDeviceConfigVersionsResponse.deserialize, - ) - return self._stubs['list_device_config_versions'] - - @property - def list_device_states(self) -> Callable[ - [device_manager.ListDeviceStatesRequest], - Awaitable[device_manager.ListDeviceStatesResponse]]: - r"""Return a callable for the list device states method over gRPC. - - Lists the last few versions of the device state in - descending order (i.e.: newest first). - - Returns: - Callable[[~.ListDeviceStatesRequest], - Awaitable[~.ListDeviceStatesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'list_device_states' not in self._stubs: - self._stubs['list_device_states'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/ListDeviceStates', - request_serializer=device_manager.ListDeviceStatesRequest.serialize, - response_deserializer=device_manager.ListDeviceStatesResponse.deserialize, - ) - return self._stubs['list_device_states'] - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - resource. Replaces any existing policy. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - 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 'set_iam_policy' not in self._stubs: - self._stubs['set_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_iam_policy'] - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy for a resource. - Returns an empty policy if the resource exists and does - not have a policy set. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - 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_iam_policy' not in self._stubs: - self._stubs['get_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse]]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns permissions that a caller has on the specified resource. - If the resource does not exist, this will return an empty set of - permissions, not a NOT_FOUND error. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - 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 'test_iam_permissions' not in self._stubs: - self._stubs['test_iam_permissions'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def send_command_to_device(self) -> Callable[ - [device_manager.SendCommandToDeviceRequest], - Awaitable[device_manager.SendCommandToDeviceResponse]]: - r"""Return a callable for the send command to device method over gRPC. - - Sends a command to the specified device. In order for a device - to be able to receive commands, it must: - - 1) be connected to Cloud IoT Core using the MQTT protocol, and - 2) be subscribed to the group of MQTT topics specified by - /devices/{device-id}/commands/#. This subscription will - receive commands at the top-level topic - /devices/{device-id}/commands as well as commands for - subfolders, like /devices/{device-id}/commands/subfolder. - Note that subscribing to specific subfolders is not - supported. If the command could not be delivered to the - device, this method will return an error; in particular, if - the device is not subscribed, this method will return - FAILED_PRECONDITION. Otherwise, this method will return OK. - If the subscription is QoS 1, at least once delivery will be - guaranteed; for QoS 0, no acknowledgment will be expected - from the device. - - Returns: - Callable[[~.SendCommandToDeviceRequest], - Awaitable[~.SendCommandToDeviceResponse]]: - 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 'send_command_to_device' not in self._stubs: - self._stubs['send_command_to_device'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/SendCommandToDevice', - request_serializer=device_manager.SendCommandToDeviceRequest.serialize, - response_deserializer=device_manager.SendCommandToDeviceResponse.deserialize, - ) - return self._stubs['send_command_to_device'] - - @property - def bind_device_to_gateway(self) -> Callable[ - [device_manager.BindDeviceToGatewayRequest], - Awaitable[device_manager.BindDeviceToGatewayResponse]]: - r"""Return a callable for the bind device to gateway method over gRPC. - - Associates the device with the gateway. - - Returns: - Callable[[~.BindDeviceToGatewayRequest], - Awaitable[~.BindDeviceToGatewayResponse]]: - 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 'bind_device_to_gateway' not in self._stubs: - self._stubs['bind_device_to_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/BindDeviceToGateway', - request_serializer=device_manager.BindDeviceToGatewayRequest.serialize, - response_deserializer=device_manager.BindDeviceToGatewayResponse.deserialize, - ) - return self._stubs['bind_device_to_gateway'] - - @property - def unbind_device_from_gateway(self) -> Callable[ - [device_manager.UnbindDeviceFromGatewayRequest], - Awaitable[device_manager.UnbindDeviceFromGatewayResponse]]: - r"""Return a callable for the unbind device from gateway method over gRPC. - - Deletes the association between the device and the - gateway. - - Returns: - Callable[[~.UnbindDeviceFromGatewayRequest], - Awaitable[~.UnbindDeviceFromGatewayResponse]]: - 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 'unbind_device_from_gateway' not in self._stubs: - self._stubs['unbind_device_from_gateway'] = self.grpc_channel.unary_unary( - '/google.cloud.iot.v1.DeviceManager/UnbindDeviceFromGateway', - request_serializer=device_manager.UnbindDeviceFromGatewayRequest.serialize, - response_deserializer=device_manager.UnbindDeviceFromGatewayResponse.deserialize, - ) - return self._stubs['unbind_device_from_gateway'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'DeviceManagerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/rest.py b/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/rest.py deleted file mode 100644 index ab82fca3..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/services/device_manager/transports/rest.py +++ /dev/null @@ -1,2535 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.iot_v1.types import device_manager -from google.cloud.iot_v1.types import resources -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -from .base import DeviceManagerTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DeviceManagerRestInterceptor: - """Interceptor for DeviceManager. - - 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 DeviceManagerRestTransport. - - .. code-block:: python - class MyCustomDeviceManagerInterceptor(DeviceManagerRestInterceptor): - def pre_bind_device_to_gateway(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_bind_device_to_gateway(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_device(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_device(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_device_registry(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_device_registry(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_device(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_device_registry(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_device(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_device(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_device_registry(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_device_registry(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_device_config_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_device_config_versions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_device_registries(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_device_registries(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_devices(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_devices(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_device_states(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_device_states(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_modify_cloud_to_device_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_modify_cloud_to_device_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_send_command_to_device(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_send_command_to_device(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_set_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_set_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_test_iam_permissions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_test_iam_permissions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_unbind_device_from_gateway(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_unbind_device_from_gateway(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_device(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_device(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_device_registry(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_device_registry(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DeviceManagerRestTransport(interceptor=MyCustomDeviceManagerInterceptor()) - client = DeviceManagerClient(transport=transport) - - - """ - def pre_bind_device_to_gateway(self, request: device_manager.BindDeviceToGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.BindDeviceToGatewayRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for bind_device_to_gateway - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_bind_device_to_gateway(self, response: device_manager.BindDeviceToGatewayResponse) -> device_manager.BindDeviceToGatewayResponse: - """Post-rpc interceptor for bind_device_to_gateway - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_create_device(self, request: device_manager.CreateDeviceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.CreateDeviceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_device - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_create_device(self, response: resources.Device) -> resources.Device: - """Post-rpc interceptor for create_device - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_create_device_registry(self, request: device_manager.CreateDeviceRegistryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.CreateDeviceRegistryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_device_registry - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_create_device_registry(self, response: resources.DeviceRegistry) -> resources.DeviceRegistry: - """Post-rpc interceptor for create_device_registry - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_delete_device(self, request: device_manager.DeleteDeviceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.DeleteDeviceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_device - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def pre_delete_device_registry(self, request: device_manager.DeleteDeviceRegistryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.DeleteDeviceRegistryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_device_registry - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def pre_get_device(self, request: device_manager.GetDeviceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.GetDeviceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_device - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_get_device(self, response: resources.Device) -> resources.Device: - """Post-rpc interceptor for get_device - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_get_device_registry(self, request: device_manager.GetDeviceRegistryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.GetDeviceRegistryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_device_registry - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_get_device_registry(self, response: resources.DeviceRegistry) -> resources.DeviceRegistry: - """Post-rpc interceptor for get_device_registry - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_get_iam_policy(self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_list_device_config_versions(self, request: device_manager.ListDeviceConfigVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.ListDeviceConfigVersionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_device_config_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_list_device_config_versions(self, response: device_manager.ListDeviceConfigVersionsResponse) -> device_manager.ListDeviceConfigVersionsResponse: - """Post-rpc interceptor for list_device_config_versions - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_list_device_registries(self, request: device_manager.ListDeviceRegistriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.ListDeviceRegistriesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_device_registries - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_list_device_registries(self, response: device_manager.ListDeviceRegistriesResponse) -> device_manager.ListDeviceRegistriesResponse: - """Post-rpc interceptor for list_device_registries - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_list_devices(self, request: device_manager.ListDevicesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.ListDevicesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_devices - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_list_devices(self, response: device_manager.ListDevicesResponse) -> device_manager.ListDevicesResponse: - """Post-rpc interceptor for list_devices - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_list_device_states(self, request: device_manager.ListDeviceStatesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.ListDeviceStatesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_device_states - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_list_device_states(self, response: device_manager.ListDeviceStatesResponse) -> device_manager.ListDeviceStatesResponse: - """Post-rpc interceptor for list_device_states - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_modify_cloud_to_device_config(self, request: device_manager.ModifyCloudToDeviceConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.ModifyCloudToDeviceConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for modify_cloud_to_device_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_modify_cloud_to_device_config(self, response: resources.DeviceConfig) -> resources.DeviceConfig: - """Post-rpc interceptor for modify_cloud_to_device_config - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_send_command_to_device(self, request: device_manager.SendCommandToDeviceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.SendCommandToDeviceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for send_command_to_device - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_send_command_to_device(self, response: device_manager.SendCommandToDeviceResponse) -> device_manager.SendCommandToDeviceResponse: - """Post-rpc interceptor for send_command_to_device - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_set_iam_policy(self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_test_iam_permissions(self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_test_iam_permissions(self, response: iam_policy_pb2.TestIamPermissionsResponse) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_unbind_device_from_gateway(self, request: device_manager.UnbindDeviceFromGatewayRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.UnbindDeviceFromGatewayRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for unbind_device_from_gateway - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_unbind_device_from_gateway(self, response: device_manager.UnbindDeviceFromGatewayResponse) -> device_manager.UnbindDeviceFromGatewayResponse: - """Post-rpc interceptor for unbind_device_from_gateway - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_update_device(self, request: device_manager.UpdateDeviceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.UpdateDeviceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_device - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_update_device(self, response: resources.Device) -> resources.Device: - """Post-rpc interceptor for update_device - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - def pre_update_device_registry(self, request: device_manager.UpdateDeviceRegistryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[device_manager.UpdateDeviceRegistryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_device_registry - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeviceManager server. - """ - return request, metadata - - def post_update_device_registry(self, response: resources.DeviceRegistry) -> resources.DeviceRegistry: - """Post-rpc interceptor for update_device_registry - - Override in a subclass to manipulate the response - after it is returned by the DeviceManager server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DeviceManagerRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DeviceManagerRestInterceptor - - -class DeviceManagerRestTransport(DeviceManagerTransport): - """REST backend transport for DeviceManager. - - Internet of Things (IoT) service. Securely connect and manage - IoT devices. - - 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 = 'cloudiot.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[DeviceManagerRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DeviceManagerRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _BindDeviceToGateway(DeviceManagerRestStub): - def __hash__(self): - return hash("BindDeviceToGateway") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.BindDeviceToGatewayRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> device_manager.BindDeviceToGatewayResponse: - r"""Call the bind device to gateway method over HTTP. - - Args: - request (~.device_manager.BindDeviceToGatewayRequest): - The request object. Request for ``BindDeviceToGateway``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.device_manager.BindDeviceToGatewayResponse: - Response for ``BindDeviceToGateway``. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/registries/*}:bindDeviceToGateway', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/registries/*/groups/*}:bindDeviceToGateway', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_bind_device_to_gateway(request, metadata) - pb_request = device_manager.BindDeviceToGatewayRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = device_manager.BindDeviceToGatewayResponse() - pb_resp = device_manager.BindDeviceToGatewayResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_bind_device_to_gateway(resp) - return resp - - class _CreateDevice(DeviceManagerRestStub): - def __hash__(self): - return hash("CreateDevice") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.CreateDeviceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.Device: - r"""Call the create device method over HTTP. - - Args: - request (~.device_manager.CreateDeviceRequest): - The request object. Request for ``CreateDevice``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.Device: - The device resource. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/registries/*}/devices', - 'body': 'device', - }, - ] - request, metadata = self._interceptor.pre_create_device(request, metadata) - pb_request = device_manager.CreateDeviceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.Device() - pb_resp = resources.Device.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_device(resp) - return resp - - class _CreateDeviceRegistry(DeviceManagerRestStub): - def __hash__(self): - return hash("CreateDeviceRegistry") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.CreateDeviceRegistryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.DeviceRegistry: - r"""Call the create device registry method over HTTP. - - Args: - request (~.device_manager.CreateDeviceRegistryRequest): - The request object. Request for ``CreateDeviceRegistry``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.DeviceRegistry: - A container for a group of devices. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/registries', - 'body': 'device_registry', - }, - ] - request, metadata = self._interceptor.pre_create_device_registry(request, metadata) - pb_request = device_manager.CreateDeviceRegistryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.DeviceRegistry() - pb_resp = resources.DeviceRegistry.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_device_registry(resp) - return resp - - class _DeleteDevice(DeviceManagerRestStub): - def __hash__(self): - return hash("DeleteDevice") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.DeleteDeviceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete device method over HTTP. - - Args: - request (~.device_manager.DeleteDeviceRequest): - The request object. Request for ``DeleteDevice``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_device(request, metadata) - pb_request = device_manager.DeleteDeviceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _DeleteDeviceRegistry(DeviceManagerRestStub): - def __hash__(self): - return hash("DeleteDeviceRegistry") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.DeleteDeviceRegistryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete device registry method over HTTP. - - Args: - request (~.device_manager.DeleteDeviceRegistryRequest): - The request object. Request for ``DeleteDeviceRegistry``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/registries/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_device_registry(request, metadata) - pb_request = device_manager.DeleteDeviceRegistryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetDevice(DeviceManagerRestStub): - def __hash__(self): - return hash("GetDevice") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.GetDeviceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.Device: - r"""Call the get device method over HTTP. - - Args: - request (~.device_manager.GetDeviceRequest): - The request object. Request for ``GetDevice``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.Device: - The device resource. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}', - }, - ] - request, metadata = self._interceptor.pre_get_device(request, metadata) - pb_request = device_manager.GetDeviceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = resources.Device() - pb_resp = resources.Device.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_device(resp) - return resp - - class _GetDeviceRegistry(DeviceManagerRestStub): - def __hash__(self): - return hash("GetDeviceRegistry") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.GetDeviceRegistryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.DeviceRegistry: - r"""Call the get device registry method over HTTP. - - Args: - request (~.device_manager.GetDeviceRegistryRequest): - The request object. Request for ``GetDeviceRegistry``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.DeviceRegistry: - A container for a group of devices. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/registries/*}', - }, - ] - request, metadata = self._interceptor.pre_get_device_registry(request, metadata) - pb_request = device_manager.GetDeviceRegistryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = resources.DeviceRegistry() - pb_resp = resources.DeviceRegistry.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_device_registry(resp) - return resp - - class _GetIamPolicy(DeviceManagerRestStub): - def __hash__(self): - return hash("GetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - r"""Call the get iam policy method over HTTP. - - Args: - request (~.iam_policy_pb2.GetIamPolicyRequest): - The request object. Request message for ``GetIamPolicy`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **JSON example:** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": [ - "user:eve@example.com" - ], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **YAML example:** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/registries/*}:getIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/registries/*/groups/*}:getIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - class _ListDeviceConfigVersions(DeviceManagerRestStub): - def __hash__(self): - return hash("ListDeviceConfigVersions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.ListDeviceConfigVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> device_manager.ListDeviceConfigVersionsResponse: - r"""Call the list device config - versions method over HTTP. - - Args: - request (~.device_manager.ListDeviceConfigVersionsRequest): - The request object. Request for ``ListDeviceConfigVersions``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.device_manager.ListDeviceConfigVersionsResponse: - Response for ``ListDeviceConfigVersions``. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}/configVersions', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}/configVersions', - }, - ] - request, metadata = self._interceptor.pre_list_device_config_versions(request, metadata) - pb_request = device_manager.ListDeviceConfigVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = device_manager.ListDeviceConfigVersionsResponse() - pb_resp = device_manager.ListDeviceConfigVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_device_config_versions(resp) - return resp - - class _ListDeviceRegistries(DeviceManagerRestStub): - def __hash__(self): - return hash("ListDeviceRegistries") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.ListDeviceRegistriesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> device_manager.ListDeviceRegistriesResponse: - r"""Call the list device registries method over HTTP. - - Args: - request (~.device_manager.ListDeviceRegistriesRequest): - The request object. Request for ``ListDeviceRegistries``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.device_manager.ListDeviceRegistriesResponse: - Response for ``ListDeviceRegistries``. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/registries', - }, - ] - request, metadata = self._interceptor.pre_list_device_registries(request, metadata) - pb_request = device_manager.ListDeviceRegistriesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = device_manager.ListDeviceRegistriesResponse() - pb_resp = device_manager.ListDeviceRegistriesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_device_registries(resp) - return resp - - class _ListDevices(DeviceManagerRestStub): - def __hash__(self): - return hash("ListDevices") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.ListDevicesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> device_manager.ListDevicesResponse: - r"""Call the list devices method over HTTP. - - Args: - request (~.device_manager.ListDevicesRequest): - The request object. Request for ``ListDevices``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.device_manager.ListDevicesResponse: - Response for ``ListDevices``. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/registries/*}/devices', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/registries/*/groups/*}/devices', - }, - ] - request, metadata = self._interceptor.pre_list_devices(request, metadata) - pb_request = device_manager.ListDevicesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = device_manager.ListDevicesResponse() - pb_resp = device_manager.ListDevicesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_devices(resp) - return resp - - class _ListDeviceStates(DeviceManagerRestStub): - def __hash__(self): - return hash("ListDeviceStates") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.ListDeviceStatesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> device_manager.ListDeviceStatesResponse: - r"""Call the list device states method over HTTP. - - Args: - request (~.device_manager.ListDeviceStatesRequest): - The request object. Request for ``ListDeviceStates``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.device_manager.ListDeviceStatesResponse: - Response for ``ListDeviceStates``. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}/states', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}/states', - }, - ] - request, metadata = self._interceptor.pre_list_device_states(request, metadata) - pb_request = device_manager.ListDeviceStatesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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 = device_manager.ListDeviceStatesResponse() - pb_resp = device_manager.ListDeviceStatesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_device_states(resp) - return resp - - class _ModifyCloudToDeviceConfig(DeviceManagerRestStub): - def __hash__(self): - return hash("ModifyCloudToDeviceConfig") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.ModifyCloudToDeviceConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.DeviceConfig: - r"""Call the modify cloud to device - config method over HTTP. - - Args: - request (~.device_manager.ModifyCloudToDeviceConfigRequest): - The request object. Request for ``ModifyCloudToDeviceConfig``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.DeviceConfig: - The device configuration. Eventually - delivered to devices. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}:modifyCloudToDeviceConfig', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}:modifyCloudToDeviceConfig', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_modify_cloud_to_device_config(request, metadata) - pb_request = device_manager.ModifyCloudToDeviceConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.DeviceConfig() - pb_resp = resources.DeviceConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_modify_cloud_to_device_config(resp) - return resp - - class _SendCommandToDevice(DeviceManagerRestStub): - def __hash__(self): - return hash("SendCommandToDevice") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.SendCommandToDeviceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> device_manager.SendCommandToDeviceResponse: - r"""Call the send command to device method over HTTP. - - Args: - request (~.device_manager.SendCommandToDeviceRequest): - The request object. Request for ``SendCommandToDevice``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.device_manager.SendCommandToDeviceResponse: - Response for ``SendCommandToDevice``. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/registries/*/devices/*}:sendCommandToDevice', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/registries/*/groups/*/devices/*}:sendCommandToDevice', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_send_command_to_device(request, metadata) - pb_request = device_manager.SendCommandToDeviceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = device_manager.SendCommandToDeviceResponse() - pb_resp = device_manager.SendCommandToDeviceResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_send_command_to_device(resp) - return resp - - class _SetIamPolicy(DeviceManagerRestStub): - def __hash__(self): - return hash("SetIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - r"""Call the set iam policy method over HTTP. - - Args: - request (~.iam_policy_pb2.SetIamPolicyRequest): - The request object. Request message for ``SetIamPolicy`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy_pb2.Policy: - An Identity and Access Management (IAM) policy, which - specifies access controls for Google Cloud resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members``, or - principals, to a single ``role``. Principals can be user - accounts, service accounts, Google groups, and domains - (such as G Suite). A ``role`` is a named list of - permissions; each ``role`` can be an IAM predefined role - or a user-created custom role. - - For some types of Google Cloud resources, a ``binding`` - can also specify a ``condition``, which is a logical - expression that allows access to a resource only if the - expression evaluates to ``true``. A condition can add - constraints based on attributes of the request, the - resource, or both. To learn which resources support - conditions in their IAM policies, see the `IAM - documentation `__. - - **JSON example:** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": [ - "user:eve@example.com" - ], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ], - "etag": "BwWWja0YfJA=", - "version": 3 - } - - **YAML example:** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - etag: BwWWja0YfJA= - version: 3 - - For a description of IAM and its features, see the `IAM - documentation `__. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/registries/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/registries/*/groups/*}:setIamPolicy', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = policy_pb2.Policy() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - class _TestIamPermissions(DeviceManagerRestStub): - def __hash__(self): - return hash("TestIamPermissions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Call the test iam permissions method over HTTP. - - Args: - request (~.iam_policy_pb2.TestIamPermissionsRequest): - The request object. Request message for ``TestIamPermissions`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/registries/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/registries/*/groups/*}:testIamPermissions', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - pb_request = request - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = iam_policy_pb2.TestIamPermissionsResponse() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - class _UnbindDeviceFromGateway(DeviceManagerRestStub): - def __hash__(self): - return hash("UnbindDeviceFromGateway") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.UnbindDeviceFromGatewayRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> device_manager.UnbindDeviceFromGatewayResponse: - r"""Call the unbind device from - gateway method over HTTP. - - Args: - request (~.device_manager.UnbindDeviceFromGatewayRequest): - The request object. Request for ``UnbindDeviceFromGateway``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.device_manager.UnbindDeviceFromGatewayResponse: - Response for ``UnbindDeviceFromGateway``. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/registries/*}:unbindDeviceFromGateway', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/registries/*/groups/*}:unbindDeviceFromGateway', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_unbind_device_from_gateway(request, metadata) - pb_request = device_manager.UnbindDeviceFromGatewayRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = device_manager.UnbindDeviceFromGatewayResponse() - pb_resp = device_manager.UnbindDeviceFromGatewayResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_unbind_device_from_gateway(resp) - return resp - - class _UpdateDevice(DeviceManagerRestStub): - def __hash__(self): - return hash("UpdateDevice") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.UpdateDeviceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.Device: - r"""Call the update device method over HTTP. - - Args: - request (~.device_manager.UpdateDeviceRequest): - The request object. Request for ``UpdateDevice``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.Device: - The device resource. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{device.name=projects/*/locations/*/registries/*/devices/*}', - 'body': 'device', - }, -{ - 'method': 'patch', - 'uri': '/v1/{device.name=projects/*/locations/*/registries/*/groups/*/devices/*}', - 'body': 'device', - }, - ] - request, metadata = self._interceptor.pre_update_device(request, metadata) - pb_request = device_manager.UpdateDeviceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.Device() - pb_resp = resources.Device.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_device(resp) - return resp - - class _UpdateDeviceRegistry(DeviceManagerRestStub): - def __hash__(self): - return hash("UpdateDeviceRegistry") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: device_manager.UpdateDeviceRegistryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.DeviceRegistry: - r"""Call the update device registry method over HTTP. - - Args: - request (~.device_manager.UpdateDeviceRegistryRequest): - The request object. Request for ``UpdateDeviceRegistry``. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.DeviceRegistry: - A container for a group of devices. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{device_registry.name=projects/*/locations/*/registries/*}', - 'body': 'device_registry', - }, - ] - request, metadata = self._interceptor.pre_update_device_registry(request, metadata) - pb_request = device_manager.UpdateDeviceRegistryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.DeviceRegistry() - pb_resp = resources.DeviceRegistry.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_device_registry(resp) - return resp - - @property - def bind_device_to_gateway(self) -> Callable[ - [device_manager.BindDeviceToGatewayRequest], - device_manager.BindDeviceToGatewayResponse]: - # 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._BindDeviceToGateway(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_device(self) -> Callable[ - [device_manager.CreateDeviceRequest], - resources.Device]: - # 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._CreateDevice(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_device_registry(self) -> Callable[ - [device_manager.CreateDeviceRegistryRequest], - resources.DeviceRegistry]: - # 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._CreateDeviceRegistry(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_device(self) -> Callable[ - [device_manager.DeleteDeviceRequest], - empty_pb2.Empty]: - # 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._DeleteDevice(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_device_registry(self) -> Callable[ - [device_manager.DeleteDeviceRegistryRequest], - empty_pb2.Empty]: - # 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._DeleteDeviceRegistry(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_device(self) -> Callable[ - [device_manager.GetDeviceRequest], - resources.Device]: - # 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._GetDevice(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_device_registry(self) -> Callable[ - [device_manager.GetDeviceRegistryRequest], - resources.DeviceRegistry]: - # 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._GetDeviceRegistry(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - policy_pb2.Policy]: - # 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._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_device_config_versions(self) -> Callable[ - [device_manager.ListDeviceConfigVersionsRequest], - device_manager.ListDeviceConfigVersionsResponse]: - # 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._ListDeviceConfigVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_device_registries(self) -> Callable[ - [device_manager.ListDeviceRegistriesRequest], - device_manager.ListDeviceRegistriesResponse]: - # 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._ListDeviceRegistries(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_devices(self) -> Callable[ - [device_manager.ListDevicesRequest], - device_manager.ListDevicesResponse]: - # 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._ListDevices(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_device_states(self) -> Callable[ - [device_manager.ListDeviceStatesRequest], - device_manager.ListDeviceStatesResponse]: - # 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._ListDeviceStates(self._session, self._host, self._interceptor) # type: ignore - - @property - def modify_cloud_to_device_config(self) -> Callable[ - [device_manager.ModifyCloudToDeviceConfigRequest], - resources.DeviceConfig]: - # 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._ModifyCloudToDeviceConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def send_command_to_device(self) -> Callable[ - [device_manager.SendCommandToDeviceRequest], - device_manager.SendCommandToDeviceResponse]: - # 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._SendCommandToDevice(self._session, self._host, self._interceptor) # type: ignore - - @property - def set_iam_policy(self) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - policy_pb2.Policy]: - # 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._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - iam_policy_pb2.TestIamPermissionsResponse]: - # 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._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - @property - def unbind_device_from_gateway(self) -> Callable[ - [device_manager.UnbindDeviceFromGatewayRequest], - device_manager.UnbindDeviceFromGatewayResponse]: - # 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._UnbindDeviceFromGateway(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_device(self) -> Callable[ - [device_manager.UpdateDeviceRequest], - resources.Device]: - # 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._UpdateDevice(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_device_registry(self) -> Callable[ - [device_manager.UpdateDeviceRegistryRequest], - resources.DeviceRegistry]: - # 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._UpdateDeviceRegistry(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DeviceManagerRestTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/iot_v1/types/__init__.py deleted file mode 100644 index 3457476c..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/types/__init__.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .device_manager import ( - BindDeviceToGatewayRequest, - BindDeviceToGatewayResponse, - CreateDeviceRegistryRequest, - CreateDeviceRequest, - DeleteDeviceRegistryRequest, - DeleteDeviceRequest, - GatewayListOptions, - GetDeviceRegistryRequest, - GetDeviceRequest, - ListDeviceConfigVersionsRequest, - ListDeviceConfigVersionsResponse, - ListDeviceRegistriesRequest, - ListDeviceRegistriesResponse, - ListDevicesRequest, - ListDevicesResponse, - ListDeviceStatesRequest, - ListDeviceStatesResponse, - ModifyCloudToDeviceConfigRequest, - SendCommandToDeviceRequest, - SendCommandToDeviceResponse, - UnbindDeviceFromGatewayRequest, - UnbindDeviceFromGatewayResponse, - UpdateDeviceRegistryRequest, - UpdateDeviceRequest, -) -from .resources import ( - Device, - DeviceConfig, - DeviceCredential, - DeviceRegistry, - DeviceState, - EventNotificationConfig, - GatewayConfig, - HttpConfig, - MqttConfig, - PublicKeyCertificate, - PublicKeyCredential, - RegistryCredential, - StateNotificationConfig, - X509CertificateDetails, - GatewayAuthMethod, - GatewayType, - HttpState, - LogLevel, - MqttState, - PublicKeyCertificateFormat, - PublicKeyFormat, -) - -__all__ = ( - 'BindDeviceToGatewayRequest', - 'BindDeviceToGatewayResponse', - 'CreateDeviceRegistryRequest', - 'CreateDeviceRequest', - 'DeleteDeviceRegistryRequest', - 'DeleteDeviceRequest', - 'GatewayListOptions', - 'GetDeviceRegistryRequest', - 'GetDeviceRequest', - 'ListDeviceConfigVersionsRequest', - 'ListDeviceConfigVersionsResponse', - 'ListDeviceRegistriesRequest', - 'ListDeviceRegistriesResponse', - 'ListDevicesRequest', - 'ListDevicesResponse', - 'ListDeviceStatesRequest', - 'ListDeviceStatesResponse', - 'ModifyCloudToDeviceConfigRequest', - 'SendCommandToDeviceRequest', - 'SendCommandToDeviceResponse', - 'UnbindDeviceFromGatewayRequest', - 'UnbindDeviceFromGatewayResponse', - 'UpdateDeviceRegistryRequest', - 'UpdateDeviceRequest', - 'Device', - 'DeviceConfig', - 'DeviceCredential', - 'DeviceRegistry', - 'DeviceState', - 'EventNotificationConfig', - 'GatewayConfig', - 'HttpConfig', - 'MqttConfig', - 'PublicKeyCertificate', - 'PublicKeyCredential', - 'RegistryCredential', - 'StateNotificationConfig', - 'X509CertificateDetails', - 'GatewayAuthMethod', - 'GatewayType', - 'HttpState', - 'LogLevel', - 'MqttState', - 'PublicKeyCertificateFormat', - 'PublicKeyFormat', -) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/types/device_manager.py b/owl-bot-staging/v1/google/cloud/iot_v1/types/device_manager.py deleted file mode 100644 index 699eabc4..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/types/device_manager.py +++ /dev/null @@ -1,688 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.iot_v1.types import resources -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.iot.v1', - manifest={ - 'CreateDeviceRegistryRequest', - 'GetDeviceRegistryRequest', - 'DeleteDeviceRegistryRequest', - 'UpdateDeviceRegistryRequest', - 'ListDeviceRegistriesRequest', - 'ListDeviceRegistriesResponse', - 'CreateDeviceRequest', - 'GetDeviceRequest', - 'UpdateDeviceRequest', - 'DeleteDeviceRequest', - 'ListDevicesRequest', - 'GatewayListOptions', - 'ListDevicesResponse', - 'ModifyCloudToDeviceConfigRequest', - 'ListDeviceConfigVersionsRequest', - 'ListDeviceConfigVersionsResponse', - 'ListDeviceStatesRequest', - 'ListDeviceStatesResponse', - 'SendCommandToDeviceRequest', - 'SendCommandToDeviceResponse', - 'BindDeviceToGatewayRequest', - 'BindDeviceToGatewayResponse', - 'UnbindDeviceFromGatewayRequest', - 'UnbindDeviceFromGatewayResponse', - }, -) - - -class CreateDeviceRegistryRequest(proto.Message): - r"""Request for ``CreateDeviceRegistry``. - - Attributes: - parent (str): - Required. The project and cloud region where this device - registry must be created. For example, - ``projects/example-project/locations/us-central1``. - device_registry (google.cloud.iot_v1.types.DeviceRegistry): - Required. The device registry. The field ``name`` must be - empty. The server will generate that field from the device - registry ``id`` provided and the ``parent`` field. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - device_registry: resources.DeviceRegistry = proto.Field( - proto.MESSAGE, - number=2, - message=resources.DeviceRegistry, - ) - - -class GetDeviceRegistryRequest(proto.Message): - r"""Request for ``GetDeviceRegistry``. - - Attributes: - name (str): - Required. The name of the device registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DeleteDeviceRegistryRequest(proto.Message): - r"""Request for ``DeleteDeviceRegistry``. - - Attributes: - name (str): - Required. The name of the device registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateDeviceRegistryRequest(proto.Message): - r"""Request for ``UpdateDeviceRegistry``. - - Attributes: - device_registry (google.cloud.iot_v1.types.DeviceRegistry): - Required. The new values for the device registry. The ``id`` - field must be empty, and the ``name`` field must indicate - the path of the resource. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Only updates the ``device_registry`` fields - indicated by this mask. The field mask must not be empty, - and it must not contain fields that are immutable or only - set by the server. Mutable top-level fields: - ``event_notification_config``, ``http_config``, - ``mqtt_config``, and ``state_notification_config``. - """ - - device_registry: resources.DeviceRegistry = proto.Field( - proto.MESSAGE, - number=1, - message=resources.DeviceRegistry, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListDeviceRegistriesRequest(proto.Message): - r"""Request for ``ListDeviceRegistries``. - - Attributes: - parent (str): - Required. The project and cloud region path. For example, - ``projects/example-project/locations/us-central1``. - page_size (int): - The maximum number of registries to return in the response. - If this value is zero, the service will select a default - size. A call may return fewer objects than requested. A - non-empty ``next_page_token`` in the response indicates that - more data is available. - page_token (str): - The value returned by the last - ``ListDeviceRegistriesResponse``; indicates that this is a - continuation of a prior ``ListDeviceRegistries`` call and - the system should return the next page of data. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListDeviceRegistriesResponse(proto.Message): - r"""Response for ``ListDeviceRegistries``. - - Attributes: - device_registries (MutableSequence[google.cloud.iot_v1.types.DeviceRegistry]): - The registries that matched the query. - next_page_token (str): - If not empty, indicates that there may be more registries - that match the request; this value should be passed in a new - ``ListDeviceRegistriesRequest``. - """ - - @property - def raw_page(self): - return self - - device_registries: MutableSequence[resources.DeviceRegistry] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.DeviceRegistry, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateDeviceRequest(proto.Message): - r"""Request for ``CreateDevice``. - - Attributes: - parent (str): - Required. The name of the device registry where this device - should be created. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - device (google.cloud.iot_v1.types.Device): - Required. The device registration details. The field - ``name`` must be empty. The server generates ``name`` from - the device registry ``id`` and the ``parent`` field. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - device: resources.Device = proto.Field( - proto.MESSAGE, - number=2, - message=resources.Device, - ) - - -class GetDeviceRequest(proto.Message): - r"""Request for ``GetDevice``. - - Attributes: - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields of the ``Device`` resource to be returned in the - response. If the field mask is unset or empty, all fields - are returned. Fields have to be provided in snake_case - format, for example: ``last_heartbeat_time``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateDeviceRequest(proto.Message): - r"""Request for ``UpdateDevice``. - - Attributes: - device (google.cloud.iot_v1.types.Device): - Required. The new values for the device. The ``id`` and - ``num_id`` fields must be empty, and the field ``name`` must - specify the name path. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\ or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Only updates the ``device`` fields indicated by - this mask. The field mask must not be empty, and it must not - contain fields that are immutable or only set by the server. - Mutable top-level fields: ``credentials``, ``blocked``, and - ``metadata`` - """ - - device: resources.Device = proto.Field( - proto.MESSAGE, - number=2, - message=resources.Device, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=3, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteDeviceRequest(proto.Message): - r"""Request for ``DeleteDevice``. - - Attributes: - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDevicesRequest(proto.Message): - r"""Request for ``ListDevices``. - - Attributes: - parent (str): - Required. The device registry path. Required. For example, - ``projects/my-project/locations/us-central1/registries/my-registry``. - device_num_ids (MutableSequence[int]): - A list of device numeric IDs. If empty, this - field is ignored. Maximum IDs: 10,000. - device_ids (MutableSequence[str]): - A list of device string IDs. For example, - ``['device0', 'device12']``. If empty, this field is - ignored. Maximum IDs: 10,000 - field_mask (google.protobuf.field_mask_pb2.FieldMask): - The fields of the ``Device`` resource to be returned in the - response. The fields ``id`` and ``num_id`` are always - returned, along with any other fields specified in - snake_case format, for example: ``last_heartbeat_time``. - gateway_list_options (google.cloud.iot_v1.types.GatewayListOptions): - Options related to gateways. - page_size (int): - The maximum number of devices to return in the response. If - this value is zero, the service will select a default size. - A call may return fewer objects than requested. A non-empty - ``next_page_token`` in the response indicates that more data - is available. - page_token (str): - The value returned by the last ``ListDevicesResponse``; - indicates that this is a continuation of a prior - ``ListDevices`` call and the system should return the next - page of data. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - device_num_ids: MutableSequence[int] = proto.RepeatedField( - proto.UINT64, - number=2, - ) - device_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - field_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=4, - message=field_mask_pb2.FieldMask, - ) - gateway_list_options: 'GatewayListOptions' = proto.Field( - proto.MESSAGE, - number=6, - message='GatewayListOptions', - ) - page_size: int = proto.Field( - proto.INT32, - number=100, - ) - page_token: str = proto.Field( - proto.STRING, - number=101, - ) - - -class GatewayListOptions(proto.Message): - r"""Options for limiting the list based on gateway type and - associations. - - 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: - gateway_type (google.cloud.iot_v1.types.GatewayType): - If ``GATEWAY`` is specified, only gateways are returned. If - ``NON_GATEWAY`` is specified, only non-gateway devices are - returned. If ``GATEWAY_TYPE_UNSPECIFIED`` is specified, all - devices are returned. - - This field is a member of `oneof`_ ``filter``. - associations_gateway_id (str): - If set, only devices associated with the specified gateway - are returned. The gateway ID can be numeric (``num_id``) or - the user-defined string (``id``). For example, if ``123`` is - specified, only devices bound to the gateway with ``num_id`` - 123 are returned. - - This field is a member of `oneof`_ ``filter``. - associations_device_id (str): - If set, returns only the gateways with which the specified - device is associated. The device ID can be numeric - (``num_id``) or the user-defined string (``id``). For - example, if ``456`` is specified, returns only the gateways - to which the device with ``num_id`` 456 is bound. - - This field is a member of `oneof`_ ``filter``. - """ - - gateway_type: resources.GatewayType = proto.Field( - proto.ENUM, - number=1, - oneof='filter', - enum=resources.GatewayType, - ) - associations_gateway_id: str = proto.Field( - proto.STRING, - number=2, - oneof='filter', - ) - associations_device_id: str = proto.Field( - proto.STRING, - number=3, - oneof='filter', - ) - - -class ListDevicesResponse(proto.Message): - r"""Response for ``ListDevices``. - - Attributes: - devices (MutableSequence[google.cloud.iot_v1.types.Device]): - The devices that match the request. - next_page_token (str): - If not empty, indicates that there may be more devices that - match the request; this value should be passed in a new - ``ListDevicesRequest``. - """ - - @property - def raw_page(self): - return self - - devices: MutableSequence[resources.Device] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.Device, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ModifyCloudToDeviceConfigRequest(proto.Message): - r"""Request for ``ModifyCloudToDeviceConfig``. - - Attributes: - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - version_to_update (int): - The version number to update. If this value - is zero, it will not check the version number of - the server and will always update the current - version; otherwise, this update will fail if the - version number found on the server does not - match this version number. This is used to - support multiple simultaneous updates without - losing data. - binary_data (bytes): - Required. The configuration data for the - device. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - version_to_update: int = proto.Field( - proto.INT64, - number=2, - ) - binary_data: bytes = proto.Field( - proto.BYTES, - number=3, - ) - - -class ListDeviceConfigVersionsRequest(proto.Message): - r"""Request for ``ListDeviceConfigVersions``. - - Attributes: - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - num_versions (int): - The number of versions to list. Versions are - listed in decreasing order of the version - number. The maximum number of versions retained - is 10. If this value is zero, it will return all - the versions available. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - num_versions: int = proto.Field( - proto.INT32, - number=2, - ) - - -class ListDeviceConfigVersionsResponse(proto.Message): - r"""Response for ``ListDeviceConfigVersions``. - - Attributes: - device_configs (MutableSequence[google.cloud.iot_v1.types.DeviceConfig]): - The device configuration for the last few - versions. Versions are listed in decreasing - order, starting from the most recent one. - """ - - device_configs: MutableSequence[resources.DeviceConfig] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.DeviceConfig, - ) - - -class ListDeviceStatesRequest(proto.Message): - r"""Request for ``ListDeviceStates``. - - Attributes: - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - num_states (int): - The number of states to list. States are - listed in descending order of update time. The - maximum number of states retained is 10. If this - value is zero, it will return all the states - available. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - num_states: int = proto.Field( - proto.INT32, - number=2, - ) - - -class ListDeviceStatesResponse(proto.Message): - r"""Response for ``ListDeviceStates``. - - Attributes: - device_states (MutableSequence[google.cloud.iot_v1.types.DeviceState]): - The last few device states. States are listed - in descending order of server update time, - starting from the most recent one. - """ - - device_states: MutableSequence[resources.DeviceState] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.DeviceState, - ) - - -class SendCommandToDeviceRequest(proto.Message): - r"""Request for ``SendCommandToDevice``. - - Attributes: - name (str): - Required. The name of the device. For example, - ``projects/p0/locations/us-central1/registries/registry0/devices/device0`` - or - ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``. - binary_data (bytes): - Required. The command data to send to the - device. - subfolder (str): - Optional subfolder for the command. If empty, - the command will be delivered to the - /devices/{device-id}/commands topic, otherwise - it will be delivered to the - /devices/{device-id}/commands/{subfolder} topic. - Multi-level subfolders are allowed. This field - must not have more than 256 characters, and must - not contain any MQTT wildcards ("+" or "#") or - null characters. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - binary_data: bytes = proto.Field( - proto.BYTES, - number=2, - ) - subfolder: str = proto.Field( - proto.STRING, - number=3, - ) - - -class SendCommandToDeviceResponse(proto.Message): - r"""Response for ``SendCommandToDevice``. - """ - - -class BindDeviceToGatewayRequest(proto.Message): - r"""Request for ``BindDeviceToGateway``. - - Attributes: - parent (str): - Required. The name of the registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - gateway_id (str): - Required. The value of ``gateway_id`` can be either the - device numeric ID or the user-defined device identifier. - device_id (str): - Required. The device to associate with the specified - gateway. The value of ``device_id`` can be either the device - numeric ID or the user-defined device identifier. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - gateway_id: str = proto.Field( - proto.STRING, - number=2, - ) - device_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class BindDeviceToGatewayResponse(proto.Message): - r"""Response for ``BindDeviceToGateway``. - """ - - -class UnbindDeviceFromGatewayRequest(proto.Message): - r"""Request for ``UnbindDeviceFromGateway``. - - Attributes: - parent (str): - Required. The name of the registry. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - gateway_id (str): - Required. The value of ``gateway_id`` can be either the - device numeric ID or the user-defined device identifier. - device_id (str): - Required. The device to disassociate from the specified - gateway. The value of ``device_id`` can be either the device - numeric ID or the user-defined device identifier. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - gateway_id: str = proto.Field( - proto.STRING, - number=2, - ) - device_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UnbindDeviceFromGatewayResponse(proto.Message): - r"""Response for ``UnbindDeviceFromGateway``. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/iot_v1/types/resources.py b/owl-bot-staging/v1/google/cloud/iot_v1/types/resources.py deleted file mode 100644 index 2fb358c5..00000000 --- a/owl-bot-staging/v1/google/cloud/iot_v1/types/resources.py +++ /dev/null @@ -1,868 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.iot.v1', - manifest={ - 'MqttState', - 'HttpState', - 'LogLevel', - 'GatewayType', - 'GatewayAuthMethod', - 'PublicKeyCertificateFormat', - 'PublicKeyFormat', - 'Device', - 'GatewayConfig', - 'DeviceRegistry', - 'MqttConfig', - 'HttpConfig', - 'EventNotificationConfig', - 'StateNotificationConfig', - 'RegistryCredential', - 'X509CertificateDetails', - 'PublicKeyCertificate', - 'DeviceCredential', - 'PublicKeyCredential', - 'DeviceConfig', - 'DeviceState', - }, -) - - -class MqttState(proto.Enum): - r"""Indicates whether an MQTT connection is enabled or disabled. - See the field description for details. - - Values: - MQTT_STATE_UNSPECIFIED (0): - No MQTT state specified. If not specified, - MQTT will be enabled by default. - MQTT_ENABLED (1): - Enables a MQTT connection. - MQTT_DISABLED (2): - Disables a MQTT connection. - """ - MQTT_STATE_UNSPECIFIED = 0 - MQTT_ENABLED = 1 - MQTT_DISABLED = 2 - - -class HttpState(proto.Enum): - r"""Indicates whether DeviceService (HTTP) is enabled or disabled - for the registry. See the field description for details. - - Values: - HTTP_STATE_UNSPECIFIED (0): - No HTTP state specified. If not specified, - DeviceService will be enabled by default. - HTTP_ENABLED (1): - Enables DeviceService (HTTP) service for the - registry. - HTTP_DISABLED (2): - Disables DeviceService (HTTP) service for the - registry. - """ - HTTP_STATE_UNSPECIFIED = 0 - HTTP_ENABLED = 1 - HTTP_DISABLED = 2 - - -class LogLevel(proto.Enum): - r"""**Beta Feature** - - The logging verbosity for device activity. Specifies which events - should be written to logs. For example, if the LogLevel is ERROR, - only events that terminate in errors will be logged. LogLevel is - inclusive; enabling INFO logging will also enable ERROR logging. - - Values: - LOG_LEVEL_UNSPECIFIED (0): - No logging specified. If not specified, - logging will be disabled. - NONE (10): - Disables logging. - ERROR (20): - Error events will be logged. - INFO (30): - Informational events will be logged, such as - connections and disconnections. - DEBUG (40): - All events will be logged. - """ - LOG_LEVEL_UNSPECIFIED = 0 - NONE = 10 - ERROR = 20 - INFO = 30 - DEBUG = 40 - - -class GatewayType(proto.Enum): - r"""Gateway type. - - Values: - GATEWAY_TYPE_UNSPECIFIED (0): - If unspecified, the device is considered a - non-gateway device. - GATEWAY (1): - The device is a gateway. - NON_GATEWAY (2): - The device is not a gateway. - """ - GATEWAY_TYPE_UNSPECIFIED = 0 - GATEWAY = 1 - NON_GATEWAY = 2 - - -class GatewayAuthMethod(proto.Enum): - r"""The gateway authorization/authentication method. This setting - determines how Cloud IoT Core authorizes/authenticate devices to - access the gateway. - - Values: - GATEWAY_AUTH_METHOD_UNSPECIFIED (0): - No authentication/authorization method - specified. No devices are allowed to access the - gateway. - ASSOCIATION_ONLY (1): - The device is authenticated through the - gateway association only. Device credentials are - ignored even if provided. - DEVICE_AUTH_TOKEN_ONLY (2): - The device is authenticated through its own - credentials. Gateway association is not checked. - ASSOCIATION_AND_DEVICE_AUTH_TOKEN (3): - The device is authenticated through both - device credentials and gateway association. The - device must be bound to the gateway and must - provide its own credentials. - """ - GATEWAY_AUTH_METHOD_UNSPECIFIED = 0 - ASSOCIATION_ONLY = 1 - DEVICE_AUTH_TOKEN_ONLY = 2 - ASSOCIATION_AND_DEVICE_AUTH_TOKEN = 3 - - -class PublicKeyCertificateFormat(proto.Enum): - r"""The supported formats for the public key. - - Values: - UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT (0): - The format has not been specified. This is an - invalid default value and must not be used. - X509_CERTIFICATE_PEM (1): - An X.509v3 certificate - (`RFC5280 `__), - encoded in base64, and wrapped by - ``-----BEGIN CERTIFICATE-----`` and - ``-----END CERTIFICATE-----``. - """ - UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT = 0 - X509_CERTIFICATE_PEM = 1 - - -class PublicKeyFormat(proto.Enum): - r"""The supported formats for the public key. - - Values: - UNSPECIFIED_PUBLIC_KEY_FORMAT (0): - The format has not been specified. This is an - invalid default value and must not be used. - RSA_PEM (3): - An RSA public key encoded in base64, and wrapped by - ``-----BEGIN PUBLIC KEY-----`` and - ``-----END PUBLIC KEY-----``. This can be used to verify - ``RS256`` signatures in JWT tokens - (`RFC7518 `__). - RSA_X509_PEM (1): - As RSA_PEM, but wrapped in an X.509v3 certificate - (`RFC5280 `__), - encoded in base64, and wrapped by - ``-----BEGIN CERTIFICATE-----`` and - ``-----END CERTIFICATE-----``. - ES256_PEM (2): - Public key for the ECDSA algorithm using P-256 and SHA-256, - encoded in base64, and wrapped by - ``-----BEGIN PUBLIC KEY-----`` and - ``-----END PUBLIC KEY-----``. This can be used to verify JWT - tokens with the ``ES256`` algorithm - (`RFC7518 `__). This - curve is defined in `OpenSSL `__ - as the ``prime256v1`` curve. - ES256_X509_PEM (4): - As ES256_PEM, but wrapped in an X.509v3 certificate - (`RFC5280 `__), - encoded in base64, and wrapped by - ``-----BEGIN CERTIFICATE-----`` and - ``-----END CERTIFICATE-----``. - """ - UNSPECIFIED_PUBLIC_KEY_FORMAT = 0 - RSA_PEM = 3 - RSA_X509_PEM = 1 - ES256_PEM = 2 - ES256_X509_PEM = 4 - - -class Device(proto.Message): - r"""The device resource. - - Attributes: - id (str): - The user-defined device identifier. The - device ID must be unique within a device - registry. - name (str): - The resource path name. For example, - ``projects/p1/locations/us-central1/registries/registry0/devices/dev0`` - or - ``projects/p1/locations/us-central1/registries/registry0/devices/{num_id}``. - When ``name`` is populated as a response from the service, - it always ends in the device numeric ID. - num_id (int): - [Output only] A server-defined unique numeric ID for the - device. This is a more compact way to identify devices, and - it is globally unique. - credentials (MutableSequence[google.cloud.iot_v1.types.DeviceCredential]): - The credentials used to authenticate this device. To allow - credential rotation without interruption, multiple device - credentials can be bound to this device. No more than 3 - credentials can be bound to a single device at a time. When - new credentials are added to a device, they are verified - against the registry credentials. For details, see the - description of the ``DeviceRegistry.credentials`` field. - last_heartbeat_time (google.protobuf.timestamp_pb2.Timestamp): - [Output only] The last time an MQTT ``PINGREQ`` was - received. This field applies only to devices connecting - through MQTT. MQTT clients usually only send ``PINGREQ`` - messages if the connection is idle, and no other messages - have been sent. Timestamps are periodically collected and - written to storage; they may be stale by a few minutes. - last_event_time (google.protobuf.timestamp_pb2.Timestamp): - [Output only] The last time a telemetry event was received. - Timestamps are periodically collected and written to - storage; they may be stale by a few minutes. - last_state_time (google.protobuf.timestamp_pb2.Timestamp): - [Output only] The last time a state event was received. - Timestamps are periodically collected and written to - storage; they may be stale by a few minutes. - last_config_ack_time (google.protobuf.timestamp_pb2.Timestamp): - [Output only] The last time a cloud-to-device config version - acknowledgment was received from the device. This field is - only for configurations sent through MQTT. - last_config_send_time (google.protobuf.timestamp_pb2.Timestamp): - [Output only] The last time a cloud-to-device config version - was sent to the device. - blocked (bool): - If a device is blocked, connections or - requests from this device will fail. Can be used - to temporarily prevent the device from - connecting if, for example, the sensor is - generating bad data and needs maintenance. - last_error_time (google.protobuf.timestamp_pb2.Timestamp): - [Output only] The time the most recent error occurred, such - as a failure to publish to Cloud Pub/Sub. This field is the - timestamp of 'last_error_status'. - last_error_status (google.rpc.status_pb2.Status): - [Output only] The error message of the most recent error, - such as a failure to publish to Cloud Pub/Sub. - 'last_error_time' is the timestamp of this field. If no - errors have occurred, this field has an empty message and - the status code 0 == OK. Otherwise, this field is expected - to have a status code other than OK. - config (google.cloud.iot_v1.types.DeviceConfig): - The most recent device configuration, which is eventually - sent from Cloud IoT Core to the device. If not present on - creation, the configuration will be initialized with an - empty payload and version value of ``1``. To update this - field after creation, use the - ``DeviceManager.ModifyCloudToDeviceConfig`` method. - state (google.cloud.iot_v1.types.DeviceState): - [Output only] The state most recently received from the - device. If no state has been reported, this field is not - present. - log_level (google.cloud.iot_v1.types.LogLevel): - **Beta Feature** - - The logging verbosity for device activity. If unspecified, - DeviceRegistry.log_level will be used. - metadata (MutableMapping[str, str]): - The metadata key-value pairs assigned to the device. This - metadata is not interpreted or indexed by Cloud IoT Core. It - can be used to add contextual information for the device. - - Keys must conform to the regular expression - [a-zA-Z][a-zA-Z0-9-_.+~%]+ and be less than 128 bytes in - length. - - Values are free-form strings. Each value must be less than - or equal to 32 KB in size. - - The total size of all keys and values must be less than 256 - KB, and the maximum number of key-value pairs is 500. - gateway_config (google.cloud.iot_v1.types.GatewayConfig): - Gateway-related configuration and state. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - num_id: int = proto.Field( - proto.UINT64, - number=3, - ) - credentials: MutableSequence['DeviceCredential'] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='DeviceCredential', - ) - last_heartbeat_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - last_event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - last_state_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=20, - message=timestamp_pb2.Timestamp, - ) - last_config_ack_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=14, - message=timestamp_pb2.Timestamp, - ) - last_config_send_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=18, - message=timestamp_pb2.Timestamp, - ) - blocked: bool = proto.Field( - proto.BOOL, - number=19, - ) - last_error_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - last_error_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=11, - message=status_pb2.Status, - ) - config: 'DeviceConfig' = proto.Field( - proto.MESSAGE, - number=13, - message='DeviceConfig', - ) - state: 'DeviceState' = proto.Field( - proto.MESSAGE, - number=16, - message='DeviceState', - ) - log_level: 'LogLevel' = proto.Field( - proto.ENUM, - number=21, - enum='LogLevel', - ) - metadata: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=17, - ) - gateway_config: 'GatewayConfig' = proto.Field( - proto.MESSAGE, - number=24, - message='GatewayConfig', - ) - - -class GatewayConfig(proto.Message): - r"""Gateway-related configuration and state. - - Attributes: - gateway_type (google.cloud.iot_v1.types.GatewayType): - Indicates whether the device is a gateway. - gateway_auth_method (google.cloud.iot_v1.types.GatewayAuthMethod): - Indicates how to authorize and/or - authenticate devices to access the gateway. - last_accessed_gateway_id (str): - [Output only] The ID of the gateway the device accessed most - recently. - last_accessed_gateway_time (google.protobuf.timestamp_pb2.Timestamp): - [Output only] The most recent time at which the device - accessed the gateway specified in ``last_accessed_gateway``. - """ - - gateway_type: 'GatewayType' = proto.Field( - proto.ENUM, - number=1, - enum='GatewayType', - ) - gateway_auth_method: 'GatewayAuthMethod' = proto.Field( - proto.ENUM, - number=2, - enum='GatewayAuthMethod', - ) - last_accessed_gateway_id: str = proto.Field( - proto.STRING, - number=3, - ) - last_accessed_gateway_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -class DeviceRegistry(proto.Message): - r"""A container for a group of devices. - - Attributes: - id (str): - The identifier of this device registry. For example, - ``myRegistry``. - name (str): - The resource path name. For example, - ``projects/example-project/locations/us-central1/registries/my-registry``. - event_notification_configs (MutableSequence[google.cloud.iot_v1.types.EventNotificationConfig]): - The configuration for notification of - telemetry events received from the device. All - telemetry events that were successfully - published by the device and acknowledged by - Cloud IoT Core are guaranteed to be delivered to - Cloud Pub/Sub. If multiple configurations match - a message, only the first matching configuration - is used. If you try to publish a device - telemetry event using MQTT without specifying a - Cloud Pub/Sub topic for the device's registry, - the connection closes automatically. If you try - to do so using an HTTP connection, an error is - returned. Up to 10 configurations may be - provided. - state_notification_config (google.cloud.iot_v1.types.StateNotificationConfig): - The configuration for notification of new - states received from the device. State updates - are guaranteed to be stored in the state - history, but notifications to Cloud Pub/Sub are - not guaranteed. For example, if permissions are - misconfigured or the specified topic doesn't - exist, no notification will be published but the - state will still be stored in Cloud IoT Core. - mqtt_config (google.cloud.iot_v1.types.MqttConfig): - The MQTT configuration for this device - registry. - http_config (google.cloud.iot_v1.types.HttpConfig): - The DeviceService (HTTP) configuration for - this device registry. - log_level (google.cloud.iot_v1.types.LogLevel): - **Beta Feature** - - The default logging verbosity for activity from devices in - this registry. The verbosity level can be overridden by - Device.log_level. - credentials (MutableSequence[google.cloud.iot_v1.types.RegistryCredential]): - The credentials used to verify the device - credentials. No more than 10 credentials can be - bound to a single registry at a time. The - verification process occurs at the time of - device creation or update. If this field is - empty, no verification is performed. Otherwise, - the credentials of a newly created device or - added credentials of an updated device should be - signed with one of these registry credentials. - - Note, however, that existing devices will never - be affected by modifications to this list of - credentials: after a device has been - successfully created in a registry, it should be - able to connect even if its registry credentials - are revoked, deleted, or modified. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - name: str = proto.Field( - proto.STRING, - number=2, - ) - event_notification_configs: MutableSequence['EventNotificationConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='EventNotificationConfig', - ) - state_notification_config: 'StateNotificationConfig' = proto.Field( - proto.MESSAGE, - number=7, - message='StateNotificationConfig', - ) - mqtt_config: 'MqttConfig' = proto.Field( - proto.MESSAGE, - number=4, - message='MqttConfig', - ) - http_config: 'HttpConfig' = proto.Field( - proto.MESSAGE, - number=9, - message='HttpConfig', - ) - log_level: 'LogLevel' = proto.Field( - proto.ENUM, - number=11, - enum='LogLevel', - ) - credentials: MutableSequence['RegistryCredential'] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message='RegistryCredential', - ) - - -class MqttConfig(proto.Message): - r"""The configuration of MQTT for a device registry. - - Attributes: - mqtt_enabled_state (google.cloud.iot_v1.types.MqttState): - If enabled, allows connections using the MQTT - protocol. Otherwise, MQTT connections to this - registry will fail. - """ - - mqtt_enabled_state: 'MqttState' = proto.Field( - proto.ENUM, - number=1, - enum='MqttState', - ) - - -class HttpConfig(proto.Message): - r"""The configuration of the HTTP bridge for a device registry. - - Attributes: - http_enabled_state (google.cloud.iot_v1.types.HttpState): - If enabled, allows devices to use - DeviceService via the HTTP protocol. Otherwise, - any requests to DeviceService will fail for this - registry. - """ - - http_enabled_state: 'HttpState' = proto.Field( - proto.ENUM, - number=1, - enum='HttpState', - ) - - -class EventNotificationConfig(proto.Message): - r"""The configuration for forwarding telemetry events. - - Attributes: - subfolder_matches (str): - If the subfolder name matches this string - exactly, this configuration will be used. The - string must not include the leading '/' - character. If empty, all strings are matched. - This field is used only for telemetry events; - subfolders are not supported for state changes. - pubsub_topic_name (str): - A Cloud Pub/Sub topic name. For example, - ``projects/myProject/topics/deviceEvents``. - """ - - subfolder_matches: str = proto.Field( - proto.STRING, - number=2, - ) - pubsub_topic_name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class StateNotificationConfig(proto.Message): - r"""The configuration for notification of new states received - from the device. - - Attributes: - pubsub_topic_name (str): - A Cloud Pub/Sub topic name. For example, - ``projects/myProject/topics/deviceEvents``. - """ - - pubsub_topic_name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class RegistryCredential(proto.Message): - r"""A server-stored registry credential used to validate device - credentials. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - public_key_certificate (google.cloud.iot_v1.types.PublicKeyCertificate): - A public key certificate used to verify the - device credentials. - - This field is a member of `oneof`_ ``credential``. - """ - - public_key_certificate: 'PublicKeyCertificate' = proto.Field( - proto.MESSAGE, - number=1, - oneof='credential', - message='PublicKeyCertificate', - ) - - -class X509CertificateDetails(proto.Message): - r"""Details of an X.509 certificate. For informational purposes - only. - - Attributes: - issuer (str): - The entity that signed the certificate. - subject (str): - The entity the certificate and public key - belong to. - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time the certificate becomes valid. - expiry_time (google.protobuf.timestamp_pb2.Timestamp): - The time the certificate becomes invalid. - signature_algorithm (str): - The algorithm used to sign the certificate. - public_key_type (str): - The type of public key in the certificate. - """ - - issuer: str = proto.Field( - proto.STRING, - number=1, - ) - subject: str = proto.Field( - proto.STRING, - number=2, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - expiry_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - signature_algorithm: str = proto.Field( - proto.STRING, - number=5, - ) - public_key_type: str = proto.Field( - proto.STRING, - number=6, - ) - - -class PublicKeyCertificate(proto.Message): - r"""A public key certificate format and data. - - Attributes: - format_ (google.cloud.iot_v1.types.PublicKeyCertificateFormat): - The certificate format. - certificate (str): - The certificate data. - x509_details (google.cloud.iot_v1.types.X509CertificateDetails): - [Output only] The certificate details. Used only for X.509 - certificates. - """ - - format_: 'PublicKeyCertificateFormat' = proto.Field( - proto.ENUM, - number=1, - enum='PublicKeyCertificateFormat', - ) - certificate: str = proto.Field( - proto.STRING, - number=2, - ) - x509_details: 'X509CertificateDetails' = proto.Field( - proto.MESSAGE, - number=3, - message='X509CertificateDetails', - ) - - -class DeviceCredential(proto.Message): - r"""A server-stored device credential used for authentication. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - public_key (google.cloud.iot_v1.types.PublicKeyCredential): - A public key used to verify the signature of - JSON Web Tokens (JWTs). When adding a new device - credential, either via device creation or via - modifications, this public key credential may be - required to be signed by one of the registry - level certificates. More specifically, if the - registry contains at least one certificate, any - new device credential must be signed by one of - the registry certificates. As a result, when the - registry contains certificates, only X.509 - certificates are accepted as device credentials. - However, if the registry does not contain a - certificate, self-signed certificates and public - keys will be accepted. New device credentials - must be different from every registry-level - certificate. - - This field is a member of `oneof`_ ``credential``. - expiration_time (google.protobuf.timestamp_pb2.Timestamp): - [Optional] The time at which this credential becomes - invalid. This credential will be ignored for new client - authentication requests after this timestamp; however, it - will not be automatically deleted. - """ - - public_key: 'PublicKeyCredential' = proto.Field( - proto.MESSAGE, - number=2, - oneof='credential', - message='PublicKeyCredential', - ) - expiration_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -class PublicKeyCredential(proto.Message): - r"""A public key format and data. - - Attributes: - format_ (google.cloud.iot_v1.types.PublicKeyFormat): - The format of the key. - key (str): - The key data. - """ - - format_: 'PublicKeyFormat' = proto.Field( - proto.ENUM, - number=1, - enum='PublicKeyFormat', - ) - key: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeviceConfig(proto.Message): - r"""The device configuration. Eventually delivered to devices. - - Attributes: - version (int): - [Output only] The version of this update. The version number - is assigned by the server, and is always greater than 0 - after device creation. The version must be 0 on the - ``CreateDevice`` request if a ``config`` is specified; the - response of ``CreateDevice`` will always have a value of 1. - cloud_update_time (google.protobuf.timestamp_pb2.Timestamp): - [Output only] The time at which this configuration version - was updated in Cloud IoT Core. This timestamp is set by the - server. - device_ack_time (google.protobuf.timestamp_pb2.Timestamp): - [Output only] The time at which Cloud IoT Core received the - acknowledgment from the device, indicating that the device - has received this configuration version. If this field is - not present, the device has not yet acknowledged that it - received this version. Note that when the config was sent to - the device, many config versions may have been available in - Cloud IoT Core while the device was disconnected, and on - connection, only the latest version is sent to the device. - Some versions may never be sent to the device, and therefore - are never acknowledged. This timestamp is set by Cloud IoT - Core. - binary_data (bytes): - The device configuration data. - """ - - version: int = proto.Field( - proto.INT64, - number=1, - ) - cloud_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - device_ack_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - binary_data: bytes = proto.Field( - proto.BYTES, - number=4, - ) - - -class DeviceState(proto.Message): - r"""The device state, as reported by the device. - - Attributes: - update_time (google.protobuf.timestamp_pb2.Timestamp): - [Output only] The time at which this state version was - updated in Cloud IoT Core. - binary_data (bytes): - The device state data. - """ - - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - binary_data: bytes = proto.Field( - proto.BYTES, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 574c5aed..00000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index a0d4d4e7..00000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/iot_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py deleted file mode 100644 index 61baf13d..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BindDeviceToGateway -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_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.cloud import iot_v1 - - -async def sample_bind_device_to_gateway(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.BindDeviceToGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - device_id="device_id_value", - ) - - # Make the request - response = await client.bind_device_to_gateway(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py deleted file mode 100644 index c48f1559..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BindDeviceToGateway -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_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.cloud import iot_v1 - - -def sample_bind_device_to_gateway(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.BindDeviceToGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - device_id="device_id_value", - ) - - # Make the request - response = client.bind_device_to_gateway(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_async.py deleted file mode 100644 index 3d1d2c3d..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDevice -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_CreateDevice_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.cloud import iot_v1 - - -async def sample_create_device(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.CreateDeviceRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_device(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_CreateDevice_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_async.py deleted file mode 100644 index 7dc503e3..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDeviceRegistry -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_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.cloud import iot_v1 - - -async def sample_create_device_registry(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.CreateDeviceRegistryRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_device_registry(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_sync.py deleted file mode 100644 index 25d2f292..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_registry_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDeviceRegistry -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_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.cloud import iot_v1 - - -def sample_create_device_registry(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.CreateDeviceRegistryRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_device_registry(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_sync.py deleted file mode 100644 index 9c35511c..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_create_device_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDevice -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_CreateDevice_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.cloud import iot_v1 - - -def sample_create_device(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.CreateDeviceRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_device(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_CreateDevice_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_async.py deleted file mode 100644 index 0e36097e..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDevice -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_DeleteDevice_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.cloud import iot_v1 - - -async def sample_delete_device(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.DeleteDeviceRequest( - name="name_value", - ) - - # Make the request - await client.delete_device(request=request) - - -# [END cloudiot_v1_generated_DeviceManager_DeleteDevice_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_async.py deleted file mode 100644 index 2a8701dd..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDeviceRegistry -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_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.cloud import iot_v1 - - -async def sample_delete_device_registry(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.DeleteDeviceRegistryRequest( - name="name_value", - ) - - # Make the request - await client.delete_device_registry(request=request) - - -# [END cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_sync.py deleted file mode 100644 index 4f0de1a9..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_registry_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDeviceRegistry -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_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.cloud import iot_v1 - - -def sample_delete_device_registry(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.DeleteDeviceRegistryRequest( - name="name_value", - ) - - # Make the request - client.delete_device_registry(request=request) - - -# [END cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_sync.py deleted file mode 100644 index 3aea32a9..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_delete_device_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDevice -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_DeleteDevice_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.cloud import iot_v1 - - -def sample_delete_device(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.DeleteDeviceRequest( - name="name_value", - ) - - # Make the request - client.delete_device(request=request) - - -# [END cloudiot_v1_generated_DeviceManager_DeleteDevice_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_async.py deleted file mode 100644 index 019c5f2e..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDevice -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_GetDevice_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.cloud import iot_v1 - - -async def sample_get_device(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.GetDeviceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_device(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_GetDevice_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_async.py deleted file mode 100644 index 6f257d39..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDeviceRegistry -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_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.cloud import iot_v1 - - -async def sample_get_device_registry(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.GetDeviceRegistryRequest( - name="name_value", - ) - - # Make the request - response = await client.get_device_registry(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_sync.py deleted file mode 100644 index d0015643..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_registry_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDeviceRegistry -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_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.cloud import iot_v1 - - -def sample_get_device_registry(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.GetDeviceRegistryRequest( - name="name_value", - ) - - # Make the request - response = client.get_device_registry(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_sync.py deleted file mode 100644 index e1df87a1..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_device_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDevice -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_GetDevice_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.cloud import iot_v1 - - -def sample_get_device(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.GetDeviceRequest( - name="name_value", - ) - - # Make the request - response = client.get_device(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_GetDevice_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_async.py deleted file mode 100644 index 00eb8cf6..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_GetIamPolicy_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.cloud import iot_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_get_iam_policy(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_GetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_sync.py deleted file mode 100644 index 28eff036..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_get_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetIamPolicy -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_GetIamPolicy_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.cloud import iot_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_get_iam_policy(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iam_policy_pb2.GetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.get_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_GetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_async.py deleted file mode 100644 index ea8b8999..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDeviceConfigVersions -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_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.cloud import iot_v1 - - -async def sample_list_device_config_versions(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceConfigVersionsRequest( - name="name_value", - ) - - # Make the request - response = await client.list_device_config_versions(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py deleted file mode 100644 index 76cdcbc4..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDeviceConfigVersions -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_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.cloud import iot_v1 - - -def sample_list_device_config_versions(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceConfigVersionsRequest( - name="name_value", - ) - - # Make the request - response = client.list_device_config_versions(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_async.py deleted file mode 100644 index 0ee9ae87..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDeviceRegistries -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_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.cloud import iot_v1 - - -async def sample_list_device_registries(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceRegistriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_device_registries(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_sync.py deleted file mode 100644 index 15262ce7..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_registries_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDeviceRegistries -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_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.cloud import iot_v1 - - -def sample_list_device_registries(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceRegistriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_device_registries(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_async.py deleted file mode 100644 index b532dc5a..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDeviceStates -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_ListDeviceStates_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.cloud import iot_v1 - - -async def sample_list_device_states(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceStatesRequest( - name="name_value", - ) - - # Make the request - response = await client.list_device_states(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_ListDeviceStates_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_sync.py deleted file mode 100644 index 09ec53f4..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_device_states_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDeviceStates -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_ListDeviceStates_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.cloud import iot_v1 - - -def sample_list_device_states(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.ListDeviceStatesRequest( - name="name_value", - ) - - # Make the request - response = client.list_device_states(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_ListDeviceStates_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_async.py deleted file mode 100644 index d392007d..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDevices -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_ListDevices_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.cloud import iot_v1 - - -async def sample_list_devices(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.ListDevicesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_devices(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudiot_v1_generated_DeviceManager_ListDevices_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_sync.py deleted file mode 100644 index 16a6b209..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_list_devices_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDevices -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_ListDevices_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.cloud import iot_v1 - - -def sample_list_devices(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.ListDevicesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_devices(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudiot_v1_generated_DeviceManager_ListDevices_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py deleted file mode 100644 index 14703599..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ModifyCloudToDeviceConfig -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_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.cloud import iot_v1 - - -async def sample_modify_cloud_to_device_config(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.ModifyCloudToDeviceConfigRequest( - name="name_value", - binary_data=b'binary_data_blob', - ) - - # Make the request - response = await client.modify_cloud_to_device_config(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py deleted file mode 100644 index bc4164eb..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ModifyCloudToDeviceConfig -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_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.cloud import iot_v1 - - -def sample_modify_cloud_to_device_config(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.ModifyCloudToDeviceConfigRequest( - name="name_value", - binary_data=b'binary_data_blob', - ) - - # Make the request - response = client.modify_cloud_to_device_config(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_async.py deleted file mode 100644 index bd1c1014..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SendCommandToDevice -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_SendCommandToDevice_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.cloud import iot_v1 - - -async def sample_send_command_to_device(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.SendCommandToDeviceRequest( - name="name_value", - binary_data=b'binary_data_blob', - ) - - # Make the request - response = await client.send_command_to_device(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_SendCommandToDevice_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_sync.py deleted file mode 100644 index 0d333f44..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_send_command_to_device_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SendCommandToDevice -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_SendCommandToDevice_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.cloud import iot_v1 - - -def sample_send_command_to_device(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.SendCommandToDeviceRequest( - name="name_value", - binary_data=b'binary_data_blob', - ) - - # Make the request - response = client.send_command_to_device(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_SendCommandToDevice_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_async.py deleted file mode 100644 index 88ed3581..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_SetIamPolicy_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.cloud import iot_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_set_iam_policy(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = await client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_SetIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_sync.py deleted file mode 100644 index 7954d439..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_set_iam_policy_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SetIamPolicy -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_SetIamPolicy_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.cloud import iot_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_set_iam_policy(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iam_policy_pb2.SetIamPolicyRequest( - resource="resource_value", - ) - - # Make the request - response = client.set_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_SetIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_async.py deleted file mode 100644 index ba456fc8..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_TestIamPermissions_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.cloud import iot_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -async def sample_test_iam_permissions(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = await client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_TestIamPermissions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py deleted file mode 100644 index 5b0f765d..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for TestIamPermissions -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_TestIamPermissions_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.cloud import iot_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore - - -def sample_test_iam_permissions(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource="resource_value", - permissions=['permissions_value1', 'permissions_value2'], - ) - - # Make the request - response = client.test_iam_permissions(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_TestIamPermissions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py deleted file mode 100644 index f4036ade..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UnbindDeviceFromGateway -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_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.cloud import iot_v1 - - -async def sample_unbind_device_from_gateway(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.UnbindDeviceFromGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - device_id="device_id_value", - ) - - # Make the request - response = await client.unbind_device_from_gateway(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py deleted file mode 100644 index 62618682..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UnbindDeviceFromGateway -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_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.cloud import iot_v1 - - -def sample_unbind_device_from_gateway(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.UnbindDeviceFromGatewayRequest( - parent="parent_value", - gateway_id="gateway_id_value", - device_id="device_id_value", - ) - - # Make the request - response = client.unbind_device_from_gateway(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_async.py deleted file mode 100644 index fe4de0a3..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDevice -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_UpdateDevice_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.cloud import iot_v1 - - -async def sample_update_device(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.UpdateDeviceRequest( - ) - - # Make the request - response = await client.update_device(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_UpdateDevice_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_async.py deleted file mode 100644 index a021e1ee..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDeviceRegistry -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_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.cloud import iot_v1 - - -async def sample_update_device_registry(): - # Create a client - client = iot_v1.DeviceManagerAsyncClient() - - # Initialize request argument(s) - request = iot_v1.UpdateDeviceRegistryRequest( - ) - - # Make the request - response = await client.update_device_registry(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_sync.py deleted file mode 100644 index 5557e07c..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_registry_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDeviceRegistry -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_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.cloud import iot_v1 - - -def sample_update_device_registry(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.UpdateDeviceRegistryRequest( - ) - - # Make the request - response = client.update_device_registry(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_sync.py deleted file mode 100644 index 8ad6706f..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudiot_v1_generated_device_manager_update_device_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDevice -# 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-cloud-iot - - -# [START cloudiot_v1_generated_DeviceManager_UpdateDevice_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.cloud import iot_v1 - - -def sample_update_device(): - # Create a client - client = iot_v1.DeviceManagerClient() - - # Initialize request argument(s) - request = iot_v1.UpdateDeviceRequest( - ) - - # Make the request - response = client.update_device(request=request) - - # Handle the response - print(response) - -# [END cloudiot_v1_generated_DeviceManager_UpdateDevice_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.iot.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.iot.v1.json deleted file mode 100644 index 017afae4..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.iot.v1.json +++ /dev/null @@ -1,3158 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.iot.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-iot", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.bind_device_to_gateway", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.BindDeviceToGateway", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "BindDeviceToGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.BindDeviceToGatewayRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "gateway_id", - "type": "str" - }, - { - "name": "device_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.BindDeviceToGatewayResponse", - "shortName": "bind_device_to_gateway" - }, - "description": "Sample for BindDeviceToGateway", - "file": "cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_bind_device_to_gateway_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.bind_device_to_gateway", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.BindDeviceToGateway", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "BindDeviceToGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.BindDeviceToGatewayRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "gateway_id", - "type": "str" - }, - { - "name": "device_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.BindDeviceToGatewayResponse", - "shortName": "bind_device_to_gateway" - }, - "description": "Sample for BindDeviceToGateway", - "file": "cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_BindDeviceToGateway_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_bind_device_to_gateway_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.create_device_registry", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.CreateDeviceRegistry", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "CreateDeviceRegistry" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.CreateDeviceRegistryRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "device_registry", - "type": "google.cloud.iot_v1.types.DeviceRegistry" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.DeviceRegistry", - "shortName": "create_device_registry" - }, - "description": "Sample for CreateDeviceRegistry", - "file": "cloudiot_v1_generated_device_manager_create_device_registry_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_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": "cloudiot_v1_generated_device_manager_create_device_registry_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.create_device_registry", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.CreateDeviceRegistry", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "CreateDeviceRegistry" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.CreateDeviceRegistryRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "device_registry", - "type": "google.cloud.iot_v1.types.DeviceRegistry" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.DeviceRegistry", - "shortName": "create_device_registry" - }, - "description": "Sample for CreateDeviceRegistry", - "file": "cloudiot_v1_generated_device_manager_create_device_registry_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_CreateDeviceRegistry_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": "cloudiot_v1_generated_device_manager_create_device_registry_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.create_device", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.CreateDevice", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "CreateDevice" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.CreateDeviceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "device", - "type": "google.cloud.iot_v1.types.Device" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.Device", - "shortName": "create_device" - }, - "description": "Sample for CreateDevice", - "file": "cloudiot_v1_generated_device_manager_create_device_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_CreateDevice_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": "cloudiot_v1_generated_device_manager_create_device_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.create_device", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.CreateDevice", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "CreateDevice" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.CreateDeviceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "device", - "type": "google.cloud.iot_v1.types.Device" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.Device", - "shortName": "create_device" - }, - "description": "Sample for CreateDevice", - "file": "cloudiot_v1_generated_device_manager_create_device_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_CreateDevice_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": "cloudiot_v1_generated_device_manager_create_device_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.delete_device_registry", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.DeleteDeviceRegistry", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "DeleteDeviceRegistry" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.DeleteDeviceRegistryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_device_registry" - }, - "description": "Sample for DeleteDeviceRegistry", - "file": "cloudiot_v1_generated_device_manager_delete_device_registry_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_delete_device_registry_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.delete_device_registry", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.DeleteDeviceRegistry", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "DeleteDeviceRegistry" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.DeleteDeviceRegistryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_device_registry" - }, - "description": "Sample for DeleteDeviceRegistry", - "file": "cloudiot_v1_generated_device_manager_delete_device_registry_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_DeleteDeviceRegistry_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_delete_device_registry_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.delete_device", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.DeleteDevice", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "DeleteDevice" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.DeleteDeviceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_device" - }, - "description": "Sample for DeleteDevice", - "file": "cloudiot_v1_generated_device_manager_delete_device_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_DeleteDevice_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_delete_device_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.delete_device", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.DeleteDevice", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "DeleteDevice" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.DeleteDeviceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_device" - }, - "description": "Sample for DeleteDevice", - "file": "cloudiot_v1_generated_device_manager_delete_device_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_DeleteDevice_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_delete_device_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.get_device_registry", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.GetDeviceRegistry", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "GetDeviceRegistry" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.GetDeviceRegistryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.DeviceRegistry", - "shortName": "get_device_registry" - }, - "description": "Sample for GetDeviceRegistry", - "file": "cloudiot_v1_generated_device_manager_get_device_registry_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_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": "cloudiot_v1_generated_device_manager_get_device_registry_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.get_device_registry", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.GetDeviceRegistry", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "GetDeviceRegistry" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.GetDeviceRegistryRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.DeviceRegistry", - "shortName": "get_device_registry" - }, - "description": "Sample for GetDeviceRegistry", - "file": "cloudiot_v1_generated_device_manager_get_device_registry_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_GetDeviceRegistry_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": "cloudiot_v1_generated_device_manager_get_device_registry_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.get_device", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.GetDevice", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "GetDevice" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.GetDeviceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.Device", - "shortName": "get_device" - }, - "description": "Sample for GetDevice", - "file": "cloudiot_v1_generated_device_manager_get_device_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_GetDevice_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": "cloudiot_v1_generated_device_manager_get_device_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.get_device", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.GetDevice", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "GetDevice" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.GetDeviceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.Device", - "shortName": "get_device" - }, - "description": "Sample for GetDevice", - "file": "cloudiot_v1_generated_device_manager_get_device_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_GetDevice_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": "cloudiot_v1_generated_device_manager_get_device_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.get_iam_policy", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.GetIamPolicy", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudiot_v1_generated_device_manager_get_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_GetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_get_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.get_iam_policy", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.GetIamPolicy", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "GetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "get_iam_policy" - }, - "description": "Sample for GetIamPolicy", - "file": "cloudiot_v1_generated_device_manager_get_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_GetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_get_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.list_device_config_versions", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceConfigVersions", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "ListDeviceConfigVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.ListDeviceConfigVersionsRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.ListDeviceConfigVersionsResponse", - "shortName": "list_device_config_versions" - }, - "description": "Sample for ListDeviceConfigVersions", - "file": "cloudiot_v1_generated_device_manager_list_device_config_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_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": "cloudiot_v1_generated_device_manager_list_device_config_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.list_device_config_versions", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceConfigVersions", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "ListDeviceConfigVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.ListDeviceConfigVersionsRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.ListDeviceConfigVersionsResponse", - "shortName": "list_device_config_versions" - }, - "description": "Sample for ListDeviceConfigVersions", - "file": "cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceConfigVersions_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": "cloudiot_v1_generated_device_manager_list_device_config_versions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.list_device_registries", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceRegistries", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "ListDeviceRegistries" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.ListDeviceRegistriesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.services.device_manager.pagers.ListDeviceRegistriesAsyncPager", - "shortName": "list_device_registries" - }, - "description": "Sample for ListDeviceRegistries", - "file": "cloudiot_v1_generated_device_manager_list_device_registries_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_list_device_registries_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.list_device_registries", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceRegistries", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "ListDeviceRegistries" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.ListDeviceRegistriesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.services.device_manager.pagers.ListDeviceRegistriesPager", - "shortName": "list_device_registries" - }, - "description": "Sample for ListDeviceRegistries", - "file": "cloudiot_v1_generated_device_manager_list_device_registries_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceRegistries_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_list_device_registries_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.list_device_states", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceStates", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "ListDeviceStates" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.ListDeviceStatesRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.ListDeviceStatesResponse", - "shortName": "list_device_states" - }, - "description": "Sample for ListDeviceStates", - "file": "cloudiot_v1_generated_device_manager_list_device_states_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceStates_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": "cloudiot_v1_generated_device_manager_list_device_states_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.list_device_states", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.ListDeviceStates", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "ListDeviceStates" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.ListDeviceStatesRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.ListDeviceStatesResponse", - "shortName": "list_device_states" - }, - "description": "Sample for ListDeviceStates", - "file": "cloudiot_v1_generated_device_manager_list_device_states_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_ListDeviceStates_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": "cloudiot_v1_generated_device_manager_list_device_states_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.list_devices", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.ListDevices", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "ListDevices" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.ListDevicesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.services.device_manager.pagers.ListDevicesAsyncPager", - "shortName": "list_devices" - }, - "description": "Sample for ListDevices", - "file": "cloudiot_v1_generated_device_manager_list_devices_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_ListDevices_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_list_devices_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.list_devices", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.ListDevices", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "ListDevices" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.ListDevicesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.services.device_manager.pagers.ListDevicesPager", - "shortName": "list_devices" - }, - "description": "Sample for ListDevices", - "file": "cloudiot_v1_generated_device_manager_list_devices_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_ListDevices_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_list_devices_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.modify_cloud_to_device_config", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.ModifyCloudToDeviceConfig", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "ModifyCloudToDeviceConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.ModifyCloudToDeviceConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "binary_data", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.DeviceConfig", - "shortName": "modify_cloud_to_device_config" - }, - "description": "Sample for ModifyCloudToDeviceConfig", - "file": "cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.modify_cloud_to_device_config", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.ModifyCloudToDeviceConfig", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "ModifyCloudToDeviceConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.ModifyCloudToDeviceConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "binary_data", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.DeviceConfig", - "shortName": "modify_cloud_to_device_config" - }, - "description": "Sample for ModifyCloudToDeviceConfig", - "file": "cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_ModifyCloudToDeviceConfig_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_modify_cloud_to_device_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.send_command_to_device", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.SendCommandToDevice", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "SendCommandToDevice" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.SendCommandToDeviceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "binary_data", - "type": "bytes" - }, - { - "name": "subfolder", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.SendCommandToDeviceResponse", - "shortName": "send_command_to_device" - }, - "description": "Sample for SendCommandToDevice", - "file": "cloudiot_v1_generated_device_manager_send_command_to_device_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_SendCommandToDevice_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_send_command_to_device_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.send_command_to_device", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.SendCommandToDevice", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "SendCommandToDevice" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.SendCommandToDeviceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "binary_data", - "type": "bytes" - }, - { - "name": "subfolder", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.SendCommandToDeviceResponse", - "shortName": "send_command_to_device" - }, - "description": "Sample for SendCommandToDevice", - "file": "cloudiot_v1_generated_device_manager_send_command_to_device_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_SendCommandToDevice_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_send_command_to_device_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.set_iam_policy", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.SetIamPolicy", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudiot_v1_generated_device_manager_set_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_SetIamPolicy_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_set_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.set_iam_policy", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.SetIamPolicy", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "SetIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.policy_pb2.Policy", - "shortName": "set_iam_policy" - }, - "description": "Sample for SetIamPolicy", - "file": "cloudiot_v1_generated_device_manager_set_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_SetIamPolicy_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_set_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.TestIamPermissions", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudiot_v1_generated_device_manager_test_iam_permissions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_TestIamPermissions_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_test_iam_permissions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.TestIamPermissions", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "permissions", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_TestIamPermissions_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 41, - "start": 39, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 42, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_test_iam_permissions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.unbind_device_from_gateway", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.UnbindDeviceFromGateway", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "UnbindDeviceFromGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.UnbindDeviceFromGatewayRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "gateway_id", - "type": "str" - }, - { - "name": "device_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.UnbindDeviceFromGatewayResponse", - "shortName": "unbind_device_from_gateway" - }, - "description": "Sample for UnbindDeviceFromGateway", - "file": "cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_unbind_device_from_gateway_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.unbind_device_from_gateway", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.UnbindDeviceFromGateway", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "UnbindDeviceFromGateway" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.UnbindDeviceFromGatewayRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "gateway_id", - "type": "str" - }, - { - "name": "device_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.UnbindDeviceFromGatewayResponse", - "shortName": "unbind_device_from_gateway" - }, - "description": "Sample for UnbindDeviceFromGateway", - "file": "cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_UnbindDeviceFromGateway_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_unbind_device_from_gateway_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.update_device_registry", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.UpdateDeviceRegistry", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "UpdateDeviceRegistry" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.UpdateDeviceRegistryRequest" - }, - { - "name": "device_registry", - "type": "google.cloud.iot_v1.types.DeviceRegistry" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.DeviceRegistry", - "shortName": "update_device_registry" - }, - "description": "Sample for UpdateDeviceRegistry", - "file": "cloudiot_v1_generated_device_manager_update_device_registry_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_update_device_registry_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.update_device_registry", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.UpdateDeviceRegistry", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "UpdateDeviceRegistry" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.UpdateDeviceRegistryRequest" - }, - { - "name": "device_registry", - "type": "google.cloud.iot_v1.types.DeviceRegistry" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.DeviceRegistry", - "shortName": "update_device_registry" - }, - "description": "Sample for UpdateDeviceRegistry", - "file": "cloudiot_v1_generated_device_manager_update_device_registry_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_UpdateDeviceRegistry_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_update_device_registry_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient", - "shortName": "DeviceManagerAsyncClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerAsyncClient.update_device", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.UpdateDevice", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "UpdateDevice" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.UpdateDeviceRequest" - }, - { - "name": "device", - "type": "google.cloud.iot_v1.types.Device" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.Device", - "shortName": "update_device" - }, - "description": "Sample for UpdateDevice", - "file": "cloudiot_v1_generated_device_manager_update_device_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_UpdateDevice_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_update_device_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.iot_v1.DeviceManagerClient", - "shortName": "DeviceManagerClient" - }, - "fullName": "google.cloud.iot_v1.DeviceManagerClient.update_device", - "method": { - "fullName": "google.cloud.iot.v1.DeviceManager.UpdateDevice", - "service": { - "fullName": "google.cloud.iot.v1.DeviceManager", - "shortName": "DeviceManager" - }, - "shortName": "UpdateDevice" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.iot_v1.types.UpdateDeviceRequest" - }, - { - "name": "device", - "type": "google.cloud.iot_v1.types.Device" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.iot_v1.types.Device", - "shortName": "update_device" - }, - "description": "Sample for UpdateDevice", - "file": "cloudiot_v1_generated_device_manager_update_device_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudiot_v1_generated_DeviceManager_UpdateDevice_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudiot_v1_generated_device_manager_update_device_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1/scripts/fixup_iot_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_iot_v1_keywords.py deleted file mode 100644 index f59d0544..00000000 --- a/owl-bot-staging/v1/scripts/fixup_iot_v1_keywords.py +++ /dev/null @@ -1,194 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class iotCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'bind_device_to_gateway': ('parent', 'gateway_id', 'device_id', ), - 'create_device': ('parent', 'device', ), - 'create_device_registry': ('parent', 'device_registry', ), - 'delete_device': ('name', ), - 'delete_device_registry': ('name', ), - 'get_device': ('name', 'field_mask', ), - 'get_device_registry': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'list_device_config_versions': ('name', 'num_versions', ), - 'list_device_registries': ('parent', 'page_size', 'page_token', ), - 'list_devices': ('parent', 'device_num_ids', 'device_ids', 'field_mask', 'gateway_list_options', 'page_size', 'page_token', ), - 'list_device_states': ('name', 'num_states', ), - 'modify_cloud_to_device_config': ('name', 'binary_data', 'version_to_update', ), - 'send_command_to_device': ('name', 'binary_data', 'subfolder', ), - 'set_iam_policy': ('resource', 'policy', 'update_mask', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'unbind_device_from_gateway': ('parent', 'gateway_id', 'device_id', ), - 'update_device': ('device', 'update_mask', ), - 'update_device_registry': ('device_registry', 'update_mask', ), - } - - 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=iotCallTransformer(), -): - """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 iot 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/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index d264052f..00000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-iot' - - -description = "Google Cloud Iot API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/iot/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -url = "https://github.com/googleapis/python-iot" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v1/testing/constraints-3.10.txt b/owl-bot-staging/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.11.txt b/owl-bot-staging/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.12.txt b/owl-bot-staging/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt deleted file mode 100644 index 2beecf99..00000000 --- a/owl-bot-staging/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/v1/testing/constraints-3.8.txt b/owl-bot-staging/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/testing/constraints-3.9.txt b/owl-bot-staging/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/iot_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/iot_v1/__init__.py deleted file mode 100644 index 231bc125..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/iot_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/iot_v1/test_device_manager.py b/owl-bot-staging/v1/tests/unit/gapic/iot_v1/test_device_manager.py deleted file mode 100644 index 1bb501dd..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/iot_v1/test_device_manager.py +++ /dev/null @@ -1,10954 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.iot_v1.services.device_manager import DeviceManagerAsyncClient -from google.cloud.iot_v1.services.device_manager import DeviceManagerClient -from google.cloud.iot_v1.services.device_manager import pagers -from google.cloud.iot_v1.services.device_manager import transports -from google.cloud.iot_v1.types import device_manager -from google.cloud.iot_v1.types import resources -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DeviceManagerClient._get_default_mtls_endpoint(None) is None - assert DeviceManagerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DeviceManagerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DeviceManagerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DeviceManagerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DeviceManagerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DeviceManagerClient, "grpc"), - (DeviceManagerAsyncClient, "grpc_asyncio"), - (DeviceManagerClient, "rest"), -]) -def test_device_manager_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 == ( - 'cloudiot.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudiot.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DeviceManagerGrpcTransport, "grpc"), - (transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DeviceManagerRestTransport, "rest"), -]) -def test_device_manager_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", [ - (DeviceManagerClient, "grpc"), - (DeviceManagerAsyncClient, "grpc_asyncio"), - (DeviceManagerClient, "rest"), -]) -def test_device_manager_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 == ( - 'cloudiot.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudiot.googleapis.com' - ) - - -def test_device_manager_client_get_transport_class(): - transport = DeviceManagerClient.get_transport_class() - available_transports = [ - transports.DeviceManagerGrpcTransport, - transports.DeviceManagerRestTransport, - ] - assert transport in available_transports - - transport = DeviceManagerClient.get_transport_class("grpc") - assert transport == transports.DeviceManagerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc"), - (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio"), - (DeviceManagerClient, transports.DeviceManagerRestTransport, "rest"), -]) -@mock.patch.object(DeviceManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerClient)) -@mock.patch.object(DeviceManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerAsyncClient)) -def test_device_manager_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(DeviceManagerClient, '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(DeviceManagerClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc", "true"), - (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc", "false"), - (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DeviceManagerClient, transports.DeviceManagerRestTransport, "rest", "true"), - (DeviceManagerClient, transports.DeviceManagerRestTransport, "rest", "false"), -]) -@mock.patch.object(DeviceManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerClient)) -@mock.patch.object(DeviceManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_device_manager_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - DeviceManagerClient, DeviceManagerAsyncClient -]) -@mock.patch.object(DeviceManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerClient)) -@mock.patch.object(DeviceManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeviceManagerAsyncClient)) -def test_device_manager_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc"), - (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio"), - (DeviceManagerClient, transports.DeviceManagerRestTransport, "rest"), -]) -def test_device_manager_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc", grpc_helpers), - (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DeviceManagerClient, transports.DeviceManagerRestTransport, "rest", None), -]) -def test_device_manager_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_device_manager_client_client_options_from_dict(): - with mock.patch('google.cloud.iot_v1.services.device_manager.transports.DeviceManagerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DeviceManagerClient( - 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", [ - (DeviceManagerClient, transports.DeviceManagerGrpcTransport, "grpc", grpc_helpers), - (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_device_manager_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudiot.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudiot', -), - scopes=None, - default_host="cloudiot.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.CreateDeviceRegistryRequest, - dict, -]) -def test_create_device_registry(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceRegistry( - id='id_value', - name='name_value', - log_level=resources.LogLevel.NONE, - ) - response = client.create_device_registry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.CreateDeviceRegistryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceRegistry) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.log_level == resources.LogLevel.NONE - - -def test_create_device_registry_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device_registry), - '__call__') as call: - client.create_device_registry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.CreateDeviceRegistryRequest() - -@pytest.mark.asyncio -async def test_create_device_registry_async(transport: str = 'grpc_asyncio', request_type=device_manager.CreateDeviceRegistryRequest): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry( - id='id_value', - name='name_value', - log_level=resources.LogLevel.NONE, - )) - response = await client.create_device_registry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.CreateDeviceRegistryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceRegistry) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.log_level == resources.LogLevel.NONE - - -@pytest.mark.asyncio -async def test_create_device_registry_async_from_dict(): - await test_create_device_registry_async(request_type=dict) - - -def test_create_device_registry_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.CreateDeviceRegistryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device_registry), - '__call__') as call: - call.return_value = resources.DeviceRegistry() - client.create_device_registry(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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_device_registry_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.CreateDeviceRegistryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device_registry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) - await client.create_device_registry(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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_device_registry_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceRegistry() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_device_registry( - parent='parent_value', - device_registry=resources.DeviceRegistry(id='id_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].device_registry - mock_val = resources.DeviceRegistry(id='id_value') - assert arg == mock_val - - -def test_create_device_registry_flattened_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_device_registry( - device_manager.CreateDeviceRegistryRequest(), - parent='parent_value', - device_registry=resources.DeviceRegistry(id='id_value'), - ) - -@pytest.mark.asyncio -async def test_create_device_registry_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceRegistry() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_device_registry( - parent='parent_value', - device_registry=resources.DeviceRegistry(id='id_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].device_registry - mock_val = resources.DeviceRegistry(id='id_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_device_registry_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_device_registry( - device_manager.CreateDeviceRegistryRequest(), - parent='parent_value', - device_registry=resources.DeviceRegistry(id='id_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.GetDeviceRegistryRequest, - dict, -]) -def test_get_device_registry(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - 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_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceRegistry( - id='id_value', - name='name_value', - log_level=resources.LogLevel.NONE, - ) - response = client.get_device_registry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.GetDeviceRegistryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceRegistry) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.log_level == resources.LogLevel.NONE - - -def test_get_device_registry_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_device_registry), - '__call__') as call: - client.get_device_registry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.GetDeviceRegistryRequest() - -@pytest.mark.asyncio -async def test_get_device_registry_async(transport: str = 'grpc_asyncio', request_type=device_manager.GetDeviceRegistryRequest): - client = DeviceManagerAsyncClient( - 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_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry( - id='id_value', - name='name_value', - log_level=resources.LogLevel.NONE, - )) - response = await client.get_device_registry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.GetDeviceRegistryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceRegistry) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.log_level == resources.LogLevel.NONE - - -@pytest.mark.asyncio -async def test_get_device_registry_async_from_dict(): - await test_get_device_registry_async(request_type=dict) - - -def test_get_device_registry_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.GetDeviceRegistryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_device_registry), - '__call__') as call: - call.return_value = resources.DeviceRegistry() - client.get_device_registry(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_device_registry_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.GetDeviceRegistryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_device_registry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) - await client.get_device_registry(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_device_registry_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceRegistry() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_device_registry( - 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_device_registry_flattened_error(): - client = DeviceManagerClient( - 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_device_registry( - device_manager.GetDeviceRegistryRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_device_registry_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceRegistry() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_device_registry( - 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_device_registry_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_device_registry( - device_manager.GetDeviceRegistryRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.UpdateDeviceRegistryRequest, - dict, -]) -def test_update_device_registry(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceRegistry( - id='id_value', - name='name_value', - log_level=resources.LogLevel.NONE, - ) - response = client.update_device_registry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.UpdateDeviceRegistryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceRegistry) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.log_level == resources.LogLevel.NONE - - -def test_update_device_registry_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device_registry), - '__call__') as call: - client.update_device_registry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.UpdateDeviceRegistryRequest() - -@pytest.mark.asyncio -async def test_update_device_registry_async(transport: str = 'grpc_asyncio', request_type=device_manager.UpdateDeviceRegistryRequest): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry( - id='id_value', - name='name_value', - log_level=resources.LogLevel.NONE, - )) - response = await client.update_device_registry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.UpdateDeviceRegistryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceRegistry) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.log_level == resources.LogLevel.NONE - - -@pytest.mark.asyncio -async def test_update_device_registry_async_from_dict(): - await test_update_device_registry_async(request_type=dict) - - -def test_update_device_registry_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.UpdateDeviceRegistryRequest() - - request.device_registry.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device_registry), - '__call__') as call: - call.return_value = resources.DeviceRegistry() - client.update_device_registry(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', - 'device_registry.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_device_registry_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.UpdateDeviceRegistryRequest() - - request.device_registry.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device_registry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) - await client.update_device_registry(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', - 'device_registry.name=name_value', - ) in kw['metadata'] - - -def test_update_device_registry_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceRegistry() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_device_registry( - device_registry=resources.DeviceRegistry(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].device_registry - mock_val = resources.DeviceRegistry(id='id_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_device_registry_flattened_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_device_registry( - device_manager.UpdateDeviceRegistryRequest(), - device_registry=resources.DeviceRegistry(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_device_registry_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceRegistry() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceRegistry()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_device_registry( - device_registry=resources.DeviceRegistry(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].device_registry - mock_val = resources.DeviceRegistry(id='id_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_device_registry_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_device_registry( - device_manager.UpdateDeviceRegistryRequest(), - device_registry=resources.DeviceRegistry(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.DeleteDeviceRegistryRequest, - dict, -]) -def test_delete_device_registry(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - 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.delete_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_device_registry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.DeleteDeviceRegistryRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_device_registry_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_device_registry), - '__call__') as call: - client.delete_device_registry() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.DeleteDeviceRegistryRequest() - -@pytest.mark.asyncio -async def test_delete_device_registry_async(transport: str = 'grpc_asyncio', request_type=device_manager.DeleteDeviceRegistryRequest): - client = DeviceManagerAsyncClient( - 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.delete_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_device_registry(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.DeleteDeviceRegistryRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_device_registry_async_from_dict(): - await test_delete_device_registry_async(request_type=dict) - - -def test_delete_device_registry_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.DeleteDeviceRegistryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_device_registry), - '__call__') as call: - call.return_value = None - client.delete_device_registry(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_delete_device_registry_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.DeleteDeviceRegistryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_device_registry), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_device_registry(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_delete_device_registry_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_device_registry( - 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_delete_device_registry_flattened_error(): - client = DeviceManagerClient( - 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.delete_device_registry( - device_manager.DeleteDeviceRegistryRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_device_registry_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_device_registry), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_device_registry( - 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_delete_device_registry_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_device_registry( - device_manager.DeleteDeviceRegistryRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.ListDeviceRegistriesRequest, - dict, -]) -def test_list_device_registries(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_registries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDeviceRegistriesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_device_registries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDeviceRegistriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeviceRegistriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_device_registries_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_registries), - '__call__') as call: - client.list_device_registries() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDeviceRegistriesRequest() - -@pytest.mark.asyncio -async def test_list_device_registries_async(transport: str = 'grpc_asyncio', request_type=device_manager.ListDeviceRegistriesRequest): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_registries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceRegistriesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_device_registries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDeviceRegistriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeviceRegistriesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_device_registries_async_from_dict(): - await test_list_device_registries_async(request_type=dict) - - -def test_list_device_registries_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.ListDeviceRegistriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_registries), - '__call__') as call: - call.return_value = device_manager.ListDeviceRegistriesResponse() - client.list_device_registries(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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_device_registries_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.ListDeviceRegistriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_registries), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceRegistriesResponse()) - await client.list_device_registries(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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_device_registries_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_registries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDeviceRegistriesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_device_registries( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_device_registries_flattened_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_device_registries( - device_manager.ListDeviceRegistriesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_device_registries_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_registries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDeviceRegistriesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceRegistriesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_device_registries( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_device_registries_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_device_registries( - device_manager.ListDeviceRegistriesRequest(), - parent='parent_value', - ) - - -def test_list_device_registries_pager(transport_name: str = "grpc"): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_registries), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - resources.DeviceRegistry(), - resources.DeviceRegistry(), - ], - next_page_token='abc', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[], - next_page_token='def', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - ], - next_page_token='ghi', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - resources.DeviceRegistry(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_device_registries(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.DeviceRegistry) - for i in results) -def test_list_device_registries_pages(transport_name: str = "grpc"): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_registries), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - resources.DeviceRegistry(), - resources.DeviceRegistry(), - ], - next_page_token='abc', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[], - next_page_token='def', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - ], - next_page_token='ghi', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - resources.DeviceRegistry(), - ], - ), - RuntimeError, - ) - pages = list(client.list_device_registries(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_device_registries_async_pager(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_registries), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - resources.DeviceRegistry(), - resources.DeviceRegistry(), - ], - next_page_token='abc', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[], - next_page_token='def', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - ], - next_page_token='ghi', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - resources.DeviceRegistry(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_device_registries(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, resources.DeviceRegistry) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_device_registries_async_pages(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_registries), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - resources.DeviceRegistry(), - resources.DeviceRegistry(), - ], - next_page_token='abc', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[], - next_page_token='def', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - ], - next_page_token='ghi', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - resources.DeviceRegistry(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_device_registries(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - device_manager.CreateDeviceRequest, - dict, -]) -def test_create_device(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Device( - id='id_value', - name='name_value', - num_id=636, - blocked=True, - log_level=resources.LogLevel.NONE, - ) - response = client.create_device(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.CreateDeviceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Device) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.num_id == 636 - assert response.blocked is True - assert response.log_level == resources.LogLevel.NONE - - -def test_create_device_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device), - '__call__') as call: - client.create_device() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.CreateDeviceRequest() - -@pytest.mark.asyncio -async def test_create_device_async(transport: str = 'grpc_asyncio', request_type=device_manager.CreateDeviceRequest): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Device( - id='id_value', - name='name_value', - num_id=636, - blocked=True, - log_level=resources.LogLevel.NONE, - )) - response = await client.create_device(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.CreateDeviceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Device) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.num_id == 636 - assert response.blocked is True - assert response.log_level == resources.LogLevel.NONE - - -@pytest.mark.asyncio -async def test_create_device_async_from_dict(): - await test_create_device_async(request_type=dict) - - -def test_create_device_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.CreateDeviceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device), - '__call__') as call: - call.return_value = resources.Device() - client.create_device(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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_device_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.CreateDeviceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) - await client.create_device(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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_device_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Device() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_device( - parent='parent_value', - device=resources.Device(id='id_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].device - mock_val = resources.Device(id='id_value') - assert arg == mock_val - - -def test_create_device_flattened_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_device( - device_manager.CreateDeviceRequest(), - parent='parent_value', - device=resources.Device(id='id_value'), - ) - -@pytest.mark.asyncio -async def test_create_device_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Device() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_device( - parent='parent_value', - device=resources.Device(id='id_value'), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].device - mock_val = resources.Device(id='id_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_device_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_device( - device_manager.CreateDeviceRequest(), - parent='parent_value', - device=resources.Device(id='id_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.GetDeviceRequest, - dict, -]) -def test_get_device(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - 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_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Device( - id='id_value', - name='name_value', - num_id=636, - blocked=True, - log_level=resources.LogLevel.NONE, - ) - response = client.get_device(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.GetDeviceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Device) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.num_id == 636 - assert response.blocked is True - assert response.log_level == resources.LogLevel.NONE - - -def test_get_device_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_device), - '__call__') as call: - client.get_device() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.GetDeviceRequest() - -@pytest.mark.asyncio -async def test_get_device_async(transport: str = 'grpc_asyncio', request_type=device_manager.GetDeviceRequest): - client = DeviceManagerAsyncClient( - 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_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Device( - id='id_value', - name='name_value', - num_id=636, - blocked=True, - log_level=resources.LogLevel.NONE, - )) - response = await client.get_device(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.GetDeviceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Device) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.num_id == 636 - assert response.blocked is True - assert response.log_level == resources.LogLevel.NONE - - -@pytest.mark.asyncio -async def test_get_device_async_from_dict(): - await test_get_device_async(request_type=dict) - - -def test_get_device_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.GetDeviceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_device), - '__call__') as call: - call.return_value = resources.Device() - client.get_device(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_device_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.GetDeviceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_device), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) - await client.get_device(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_device_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Device() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_device( - 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_device_flattened_error(): - client = DeviceManagerClient( - 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_device( - device_manager.GetDeviceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_device_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Device() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_device( - 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_device_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_device( - device_manager.GetDeviceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.UpdateDeviceRequest, - dict, -]) -def test_update_device(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Device( - id='id_value', - name='name_value', - num_id=636, - blocked=True, - log_level=resources.LogLevel.NONE, - ) - response = client.update_device(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.UpdateDeviceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Device) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.num_id == 636 - assert response.blocked is True - assert response.log_level == resources.LogLevel.NONE - - -def test_update_device_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device), - '__call__') as call: - client.update_device() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.UpdateDeviceRequest() - -@pytest.mark.asyncio -async def test_update_device_async(transport: str = 'grpc_asyncio', request_type=device_manager.UpdateDeviceRequest): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Device( - id='id_value', - name='name_value', - num_id=636, - blocked=True, - log_level=resources.LogLevel.NONE, - )) - response = await client.update_device(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.UpdateDeviceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Device) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.num_id == 636 - assert response.blocked is True - assert response.log_level == resources.LogLevel.NONE - - -@pytest.mark.asyncio -async def test_update_device_async_from_dict(): - await test_update_device_async(request_type=dict) - - -def test_update_device_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.UpdateDeviceRequest() - - request.device.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device), - '__call__') as call: - call.return_value = resources.Device() - client.update_device(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', - 'device.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_device_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.UpdateDeviceRequest() - - request.device.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) - await client.update_device(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', - 'device.name=name_value', - ) in kw['metadata'] - - -def test_update_device_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Device() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_device( - device=resources.Device(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].device - mock_val = resources.Device(id='id_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_device_flattened_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_device( - device_manager.UpdateDeviceRequest(), - device=resources.Device(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_device_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Device() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Device()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_device( - device=resources.Device(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].device - mock_val = resources.Device(id='id_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_device_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_device( - device_manager.UpdateDeviceRequest(), - device=resources.Device(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.DeleteDeviceRequest, - dict, -]) -def test_delete_device(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - 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.delete_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_device(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.DeleteDeviceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_device_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_device), - '__call__') as call: - client.delete_device() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.DeleteDeviceRequest() - -@pytest.mark.asyncio -async def test_delete_device_async(transport: str = 'grpc_asyncio', request_type=device_manager.DeleteDeviceRequest): - client = DeviceManagerAsyncClient( - 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.delete_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_device(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.DeleteDeviceRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_device_async_from_dict(): - await test_delete_device_async(request_type=dict) - - -def test_delete_device_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.DeleteDeviceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_device), - '__call__') as call: - call.return_value = None - client.delete_device(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_delete_device_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.DeleteDeviceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_device), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_device(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_delete_device_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_device( - 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_delete_device_flattened_error(): - client = DeviceManagerClient( - 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.delete_device( - device_manager.DeleteDeviceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_device_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_device( - 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_delete_device_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_device( - device_manager.DeleteDeviceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.ListDevicesRequest, - dict, -]) -def test_list_devices(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_devices), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDevicesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_devices(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDevicesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDevicesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_devices_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_devices), - '__call__') as call: - client.list_devices() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDevicesRequest() - -@pytest.mark.asyncio -async def test_list_devices_async(transport: str = 'grpc_asyncio', request_type=device_manager.ListDevicesRequest): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_devices), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDevicesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_devices(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDevicesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDevicesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_devices_async_from_dict(): - await test_list_devices_async(request_type=dict) - - -def test_list_devices_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.ListDevicesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_devices), - '__call__') as call: - call.return_value = device_manager.ListDevicesResponse() - client.list_devices(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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_devices_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.ListDevicesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_devices), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDevicesResponse()) - await client.list_devices(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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_devices_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_devices), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDevicesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_devices( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_devices_flattened_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_devices( - device_manager.ListDevicesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_devices_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_devices), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDevicesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDevicesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_devices( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_devices_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_devices( - device_manager.ListDevicesRequest(), - parent='parent_value', - ) - - -def test_list_devices_pager(transport_name: str = "grpc"): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_devices), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - resources.Device(), - resources.Device(), - ], - next_page_token='abc', - ), - device_manager.ListDevicesResponse( - devices=[], - next_page_token='def', - ), - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - ], - next_page_token='ghi', - ), - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - resources.Device(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_devices(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Device) - for i in results) -def test_list_devices_pages(transport_name: str = "grpc"): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_devices), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - resources.Device(), - resources.Device(), - ], - next_page_token='abc', - ), - device_manager.ListDevicesResponse( - devices=[], - next_page_token='def', - ), - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - ], - next_page_token='ghi', - ), - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - resources.Device(), - ], - ), - RuntimeError, - ) - pages = list(client.list_devices(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_devices_async_pager(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_devices), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - resources.Device(), - resources.Device(), - ], - next_page_token='abc', - ), - device_manager.ListDevicesResponse( - devices=[], - next_page_token='def', - ), - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - ], - next_page_token='ghi', - ), - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - resources.Device(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_devices(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, resources.Device) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_devices_async_pages(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_devices), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - resources.Device(), - resources.Device(), - ], - next_page_token='abc', - ), - device_manager.ListDevicesResponse( - devices=[], - next_page_token='def', - ), - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - ], - next_page_token='ghi', - ), - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - resources.Device(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_devices(request={})).pages: # pragma: no branch - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - device_manager.ModifyCloudToDeviceConfigRequest, - dict, -]) -def test_modify_cloud_to_device_config(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - 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.modify_cloud_to_device_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceConfig( - version=774, - binary_data=b'binary_data_blob', - ) - response = client.modify_cloud_to_device_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ModifyCloudToDeviceConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceConfig) - assert response.version == 774 - assert response.binary_data == b'binary_data_blob' - - -def test_modify_cloud_to_device_config_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_cloud_to_device_config), - '__call__') as call: - client.modify_cloud_to_device_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ModifyCloudToDeviceConfigRequest() - -@pytest.mark.asyncio -async def test_modify_cloud_to_device_config_async(transport: str = 'grpc_asyncio', request_type=device_manager.ModifyCloudToDeviceConfigRequest): - client = DeviceManagerAsyncClient( - 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.modify_cloud_to_device_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceConfig( - version=774, - binary_data=b'binary_data_blob', - )) - response = await client.modify_cloud_to_device_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ModifyCloudToDeviceConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceConfig) - assert response.version == 774 - assert response.binary_data == b'binary_data_blob' - - -@pytest.mark.asyncio -async def test_modify_cloud_to_device_config_async_from_dict(): - await test_modify_cloud_to_device_config_async(request_type=dict) - - -def test_modify_cloud_to_device_config_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.ModifyCloudToDeviceConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_cloud_to_device_config), - '__call__') as call: - call.return_value = resources.DeviceConfig() - client.modify_cloud_to_device_config(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_modify_cloud_to_device_config_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.ModifyCloudToDeviceConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_cloud_to_device_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceConfig()) - await client.modify_cloud_to_device_config(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_modify_cloud_to_device_config_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_cloud_to_device_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.modify_cloud_to_device_config( - name='name_value', - binary_data=b'binary_data_blob', - ) - - # 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 - arg = args[0].binary_data - mock_val = b'binary_data_blob' - assert arg == mock_val - - -def test_modify_cloud_to_device_config_flattened_error(): - client = DeviceManagerClient( - 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.modify_cloud_to_device_config( - device_manager.ModifyCloudToDeviceConfigRequest(), - name='name_value', - binary_data=b'binary_data_blob', - ) - -@pytest.mark.asyncio -async def test_modify_cloud_to_device_config_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.modify_cloud_to_device_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DeviceConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DeviceConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.modify_cloud_to_device_config( - name='name_value', - binary_data=b'binary_data_blob', - ) - - # 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 - arg = args[0].binary_data - mock_val = b'binary_data_blob' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_modify_cloud_to_device_config_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.modify_cloud_to_device_config( - device_manager.ModifyCloudToDeviceConfigRequest(), - name='name_value', - binary_data=b'binary_data_blob', - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.ListDeviceConfigVersionsRequest, - dict, -]) -def test_list_device_config_versions(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_config_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDeviceConfigVersionsResponse( - ) - response = client.list_device_config_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDeviceConfigVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.ListDeviceConfigVersionsResponse) - - -def test_list_device_config_versions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_config_versions), - '__call__') as call: - client.list_device_config_versions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDeviceConfigVersionsRequest() - -@pytest.mark.asyncio -async def test_list_device_config_versions_async(transport: str = 'grpc_asyncio', request_type=device_manager.ListDeviceConfigVersionsRequest): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_config_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceConfigVersionsResponse( - )) - response = await client.list_device_config_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDeviceConfigVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.ListDeviceConfigVersionsResponse) - - -@pytest.mark.asyncio -async def test_list_device_config_versions_async_from_dict(): - await test_list_device_config_versions_async(request_type=dict) - - -def test_list_device_config_versions_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.ListDeviceConfigVersionsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_config_versions), - '__call__') as call: - call.return_value = device_manager.ListDeviceConfigVersionsResponse() - client.list_device_config_versions(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_list_device_config_versions_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.ListDeviceConfigVersionsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_config_versions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceConfigVersionsResponse()) - await client.list_device_config_versions(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_list_device_config_versions_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_config_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDeviceConfigVersionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_device_config_versions( - 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_list_device_config_versions_flattened_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_device_config_versions( - device_manager.ListDeviceConfigVersionsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_list_device_config_versions_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_config_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDeviceConfigVersionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceConfigVersionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_device_config_versions( - 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_list_device_config_versions_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_device_config_versions( - device_manager.ListDeviceConfigVersionsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.ListDeviceStatesRequest, - dict, -]) -def test_list_device_states(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_states), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDeviceStatesResponse( - ) - response = client.list_device_states(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDeviceStatesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.ListDeviceStatesResponse) - - -def test_list_device_states_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_states), - '__call__') as call: - client.list_device_states() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDeviceStatesRequest() - -@pytest.mark.asyncio -async def test_list_device_states_async(transport: str = 'grpc_asyncio', request_type=device_manager.ListDeviceStatesRequest): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_states), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceStatesResponse( - )) - response = await client.list_device_states(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.ListDeviceStatesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.ListDeviceStatesResponse) - - -@pytest.mark.asyncio -async def test_list_device_states_async_from_dict(): - await test_list_device_states_async(request_type=dict) - - -def test_list_device_states_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.ListDeviceStatesRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_states), - '__call__') as call: - call.return_value = device_manager.ListDeviceStatesResponse() - client.list_device_states(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_list_device_states_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.ListDeviceStatesRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_states), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceStatesResponse()) - await client.list_device_states(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_list_device_states_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_states), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDeviceStatesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_device_states( - 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_list_device_states_flattened_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_device_states( - device_manager.ListDeviceStatesRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_list_device_states_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_device_states), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.ListDeviceStatesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.ListDeviceStatesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_device_states( - 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_list_device_states_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_device_states( - device_manager.ListDeviceStatesRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - 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.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - response = client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_set_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = DeviceManagerAsyncClient( - 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.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( - version=774, - etag=b'etag_blob', - )) - response = await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -@pytest.mark.asyncio -async def test_set_iam_policy_async_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = DeviceManagerClient( - 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 = iam_policy_pb2.SetIamPolicyRequest() - - request.resource = 'resource_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - call.return_value = policy_pb2.Policy() - client.set_iam_policy(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', - 'resource=resource_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = iam_policy_pb2.SetIamPolicyRequest() - - request.resource = 'resource_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.set_iam_policy(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', - 'resource=resource_value', - ) in kw['metadata'] - -def test_set_iam_policy_from_dict_foreign(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.set_iam_policy(request={ - 'resource': 'resource_value', - 'policy': policy_pb2.Policy(version=774), - 'update_mask': field_mask_pb2.FieldMask(paths=['paths_value']), - } - ) - call.assert_called() - - -def test_set_iam_policy_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_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].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_set_iam_policy_flattened_error(): - client = DeviceManagerClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_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].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - 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_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_get_iam_policy_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = DeviceManagerAsyncClient( - 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_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy( - version=774, - etag=b'etag_blob', - )) - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -@pytest.mark.asyncio -async def test_get_iam_policy_async_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = DeviceManagerClient( - 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 = iam_policy_pb2.GetIamPolicyRequest() - - request.resource = 'resource_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - call.return_value = policy_pb2.Policy() - client.get_iam_policy(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', - 'resource=resource_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = iam_policy_pb2.GetIamPolicyRequest() - - request.resource = 'resource_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - await client.get_iam_policy(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', - 'resource=resource_value', - ) in kw['metadata'] - -def test_get_iam_policy_from_dict_foreign(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - response = client.get_iam_policy(request={ - 'resource': 'resource_value', - 'options': options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_get_iam_policy_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_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].resource - mock_val = 'resource_value' - assert arg == mock_val - - -def test_get_iam_policy_flattened_error(): - client = DeviceManagerClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_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].resource - mock_val = 'resource_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - 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.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - - -def test_test_iam_permissions_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = DeviceManagerAsyncClient( - 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.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - )) - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = DeviceManagerClient( - 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 = iam_policy_pb2.TestIamPermissionsRequest() - - request.resource = 'resource_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - client.test_iam_permissions(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', - 'resource=resource_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = iam_policy_pb2.TestIamPermissionsRequest() - - request.resource = 'resource_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - await client.test_iam_permissions(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', - 'resource=resource_value', - ) in kw['metadata'] - -def test_test_iam_permissions_from_dict_foreign(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - response = client.test_iam_permissions(request={ - 'resource': 'resource_value', - 'permissions': ['permissions_value'], - } - ) - call.assert_called() - - -def test_test_iam_permissions_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_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].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - - -def test_test_iam_permissions_flattened_error(): - client = DeviceManagerClient( - 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.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_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].resource - mock_val = 'resource_value' - assert arg == mock_val - arg = args[0].permissions - mock_val = ['permissions_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.SendCommandToDeviceRequest, - dict, -]) -def test_send_command_to_device(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - 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.send_command_to_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.SendCommandToDeviceResponse( - ) - response = client.send_command_to_device(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.SendCommandToDeviceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.SendCommandToDeviceResponse) - - -def test_send_command_to_device_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.send_command_to_device), - '__call__') as call: - client.send_command_to_device() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.SendCommandToDeviceRequest() - -@pytest.mark.asyncio -async def test_send_command_to_device_async(transport: str = 'grpc_asyncio', request_type=device_manager.SendCommandToDeviceRequest): - client = DeviceManagerAsyncClient( - 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.send_command_to_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.SendCommandToDeviceResponse( - )) - response = await client.send_command_to_device(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.SendCommandToDeviceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.SendCommandToDeviceResponse) - - -@pytest.mark.asyncio -async def test_send_command_to_device_async_from_dict(): - await test_send_command_to_device_async(request_type=dict) - - -def test_send_command_to_device_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.SendCommandToDeviceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.send_command_to_device), - '__call__') as call: - call.return_value = device_manager.SendCommandToDeviceResponse() - client.send_command_to_device(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_send_command_to_device_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.SendCommandToDeviceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.send_command_to_device), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.SendCommandToDeviceResponse()) - await client.send_command_to_device(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_send_command_to_device_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.send_command_to_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.SendCommandToDeviceResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.send_command_to_device( - name='name_value', - binary_data=b'binary_data_blob', - subfolder='subfolder_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 - arg = args[0].binary_data - mock_val = b'binary_data_blob' - assert arg == mock_val - arg = args[0].subfolder - mock_val = 'subfolder_value' - assert arg == mock_val - - -def test_send_command_to_device_flattened_error(): - client = DeviceManagerClient( - 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.send_command_to_device( - device_manager.SendCommandToDeviceRequest(), - name='name_value', - binary_data=b'binary_data_blob', - subfolder='subfolder_value', - ) - -@pytest.mark.asyncio -async def test_send_command_to_device_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.send_command_to_device), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.SendCommandToDeviceResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.SendCommandToDeviceResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.send_command_to_device( - name='name_value', - binary_data=b'binary_data_blob', - subfolder='subfolder_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 - arg = args[0].binary_data - mock_val = b'binary_data_blob' - assert arg == mock_val - arg = args[0].subfolder - mock_val = 'subfolder_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_send_command_to_device_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.send_command_to_device( - device_manager.SendCommandToDeviceRequest(), - name='name_value', - binary_data=b'binary_data_blob', - subfolder='subfolder_value', - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.BindDeviceToGatewayRequest, - dict, -]) -def test_bind_device_to_gateway(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - 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.bind_device_to_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.BindDeviceToGatewayResponse( - ) - response = client.bind_device_to_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.BindDeviceToGatewayRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.BindDeviceToGatewayResponse) - - -def test_bind_device_to_gateway_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bind_device_to_gateway), - '__call__') as call: - client.bind_device_to_gateway() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.BindDeviceToGatewayRequest() - -@pytest.mark.asyncio -async def test_bind_device_to_gateway_async(transport: str = 'grpc_asyncio', request_type=device_manager.BindDeviceToGatewayRequest): - client = DeviceManagerAsyncClient( - 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.bind_device_to_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.BindDeviceToGatewayResponse( - )) - response = await client.bind_device_to_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.BindDeviceToGatewayRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.BindDeviceToGatewayResponse) - - -@pytest.mark.asyncio -async def test_bind_device_to_gateway_async_from_dict(): - await test_bind_device_to_gateway_async(request_type=dict) - - -def test_bind_device_to_gateway_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.BindDeviceToGatewayRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bind_device_to_gateway), - '__call__') as call: - call.return_value = device_manager.BindDeviceToGatewayResponse() - client.bind_device_to_gateway(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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_bind_device_to_gateway_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.BindDeviceToGatewayRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bind_device_to_gateway), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.BindDeviceToGatewayResponse()) - await client.bind_device_to_gateway(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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_bind_device_to_gateway_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bind_device_to_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.BindDeviceToGatewayResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.bind_device_to_gateway( - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].gateway_id - mock_val = 'gateway_id_value' - assert arg == mock_val - arg = args[0].device_id - mock_val = 'device_id_value' - assert arg == mock_val - - -def test_bind_device_to_gateway_flattened_error(): - client = DeviceManagerClient( - 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.bind_device_to_gateway( - device_manager.BindDeviceToGatewayRequest(), - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - -@pytest.mark.asyncio -async def test_bind_device_to_gateway_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.bind_device_to_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.BindDeviceToGatewayResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.BindDeviceToGatewayResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.bind_device_to_gateway( - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].gateway_id - mock_val = 'gateway_id_value' - assert arg == mock_val - arg = args[0].device_id - mock_val = 'device_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_bind_device_to_gateway_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.bind_device_to_gateway( - device_manager.BindDeviceToGatewayRequest(), - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.UnbindDeviceFromGatewayRequest, - dict, -]) -def test_unbind_device_from_gateway(request_type, transport: str = 'grpc'): - client = DeviceManagerClient( - 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.unbind_device_from_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.UnbindDeviceFromGatewayResponse( - ) - response = client.unbind_device_from_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.UnbindDeviceFromGatewayRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.UnbindDeviceFromGatewayResponse) - - -def test_unbind_device_from_gateway_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unbind_device_from_gateway), - '__call__') as call: - client.unbind_device_from_gateway() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.UnbindDeviceFromGatewayRequest() - -@pytest.mark.asyncio -async def test_unbind_device_from_gateway_async(transport: str = 'grpc_asyncio', request_type=device_manager.UnbindDeviceFromGatewayRequest): - client = DeviceManagerAsyncClient( - 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.unbind_device_from_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(device_manager.UnbindDeviceFromGatewayResponse( - )) - response = await client.unbind_device_from_gateway(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == device_manager.UnbindDeviceFromGatewayRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.UnbindDeviceFromGatewayResponse) - - -@pytest.mark.asyncio -async def test_unbind_device_from_gateway_async_from_dict(): - await test_unbind_device_from_gateway_async(request_type=dict) - - -def test_unbind_device_from_gateway_field_headers(): - client = DeviceManagerClient( - 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 = device_manager.UnbindDeviceFromGatewayRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unbind_device_from_gateway), - '__call__') as call: - call.return_value = device_manager.UnbindDeviceFromGatewayResponse() - client.unbind_device_from_gateway(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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_unbind_device_from_gateway_field_headers_async(): - client = DeviceManagerAsyncClient( - 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 = device_manager.UnbindDeviceFromGatewayRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unbind_device_from_gateway), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.UnbindDeviceFromGatewayResponse()) - await client.unbind_device_from_gateway(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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_unbind_device_from_gateway_flattened(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unbind_device_from_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.UnbindDeviceFromGatewayResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.unbind_device_from_gateway( - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].gateway_id - mock_val = 'gateway_id_value' - assert arg == mock_val - arg = args[0].device_id - mock_val = 'device_id_value' - assert arg == mock_val - - -def test_unbind_device_from_gateway_flattened_error(): - client = DeviceManagerClient( - 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.unbind_device_from_gateway( - device_manager.UnbindDeviceFromGatewayRequest(), - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - -@pytest.mark.asyncio -async def test_unbind_device_from_gateway_flattened_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unbind_device_from_gateway), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = device_manager.UnbindDeviceFromGatewayResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(device_manager.UnbindDeviceFromGatewayResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.unbind_device_from_gateway( - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].gateway_id - mock_val = 'gateway_id_value' - assert arg == mock_val - arg = args[0].device_id - mock_val = 'device_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_unbind_device_from_gateway_flattened_error_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.unbind_device_from_gateway( - device_manager.UnbindDeviceFromGatewayRequest(), - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.CreateDeviceRegistryRequest, - dict, -]) -def test_create_device_registry_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["device_registry"] = {'id': 'id_value', 'name': 'name_value', 'event_notification_configs': [{'subfolder_matches': 'subfolder_matches_value', 'pubsub_topic_name': 'pubsub_topic_name_value'}], 'state_notification_config': {'pubsub_topic_name': 'pubsub_topic_name_value'}, 'mqtt_config': {'mqtt_enabled_state': 1}, 'http_config': {'http_enabled_state': 1}, 'log_level': 10, 'credentials': [{'public_key_certificate': {'format_': 1, 'certificate': 'certificate_value', 'x509_details': {'issuer': 'issuer_value', 'subject': 'subject_value', 'start_time': {'seconds': 751, 'nanos': 543}, 'expiry_time': {}, 'signature_algorithm': 'signature_algorithm_value', 'public_key_type': 'public_key_type_value'}}}]} - 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 = resources.DeviceRegistry( - id='id_value', - name='name_value', - log_level=resources.LogLevel.NONE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.DeviceRegistry.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_device_registry(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceRegistry) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.log_level == resources.LogLevel.NONE - - -def test_create_device_registry_rest_required_fields(request_type=device_manager.CreateDeviceRegistryRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_device_registry._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_device_registry._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.DeviceRegistry() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = resources.DeviceRegistry.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_device_registry(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_device_registry_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_device_registry._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "deviceRegistry", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_device_registry_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_create_device_registry") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_create_device_registry") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.CreateDeviceRegistryRequest.pb(device_manager.CreateDeviceRegistryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.DeviceRegistry.to_json(resources.DeviceRegistry()) - - request = device_manager.CreateDeviceRegistryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.DeviceRegistry() - - client.create_device_registry(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_device_registry_rest_bad_request(transport: str = 'rest', request_type=device_manager.CreateDeviceRegistryRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["device_registry"] = {'id': 'id_value', 'name': 'name_value', 'event_notification_configs': [{'subfolder_matches': 'subfolder_matches_value', 'pubsub_topic_name': 'pubsub_topic_name_value'}], 'state_notification_config': {'pubsub_topic_name': 'pubsub_topic_name_value'}, 'mqtt_config': {'mqtt_enabled_state': 1}, 'http_config': {'http_enabled_state': 1}, 'log_level': 10, 'credentials': [{'public_key_certificate': {'format_': 1, 'certificate': 'certificate_value', 'x509_details': {'issuer': 'issuer_value', 'subject': 'subject_value', 'start_time': {'seconds': 751, 'nanos': 543}, 'expiry_time': {}, 'signature_algorithm': 'signature_algorithm_value', 'public_key_type': 'public_key_type_value'}}}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_device_registry(request) - - -def test_create_device_registry_rest_flattened(): - client = DeviceManagerClient( - 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 = resources.DeviceRegistry() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - device_registry=resources.DeviceRegistry(id='id_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.DeviceRegistry.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_device_registry(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/registries" % client.transport._host, args[1]) - - -def test_create_device_registry_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_device_registry( - device_manager.CreateDeviceRegistryRequest(), - parent='parent_value', - device_registry=resources.DeviceRegistry(id='id_value'), - ) - - -def test_create_device_registry_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.GetDeviceRegistryRequest, - dict, -]) -def test_get_device_registry_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3'} - 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 = resources.DeviceRegistry( - id='id_value', - name='name_value', - log_level=resources.LogLevel.NONE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.DeviceRegistry.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_device_registry(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceRegistry) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.log_level == resources.LogLevel.NONE - - -def test_get_device_registry_rest_required_fields(request_type=device_manager.GetDeviceRegistryRequest): - transport_class = transports.DeviceManagerRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_device_registry._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_device_registry._get_unset_required_fields(jsonified_request) - 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 = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.DeviceRegistry() - # 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 - - pb_return_value = resources.DeviceRegistry.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_device_registry(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_device_registry_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_device_registry._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_device_registry_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_get_device_registry") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_get_device_registry") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.GetDeviceRegistryRequest.pb(device_manager.GetDeviceRegistryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.DeviceRegistry.to_json(resources.DeviceRegistry()) - - request = device_manager.GetDeviceRegistryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.DeviceRegistry() - - client.get_device_registry(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_device_registry_rest_bad_request(transport: str = 'rest', request_type=device_manager.GetDeviceRegistryRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_device_registry(request) - - -def test_get_device_registry_rest_flattened(): - client = DeviceManagerClient( - 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 = resources.DeviceRegistry() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3'} - - # 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 - pb_return_value = resources.DeviceRegistry.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_device_registry(**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=projects/*/locations/*/registries/*}" % client.transport._host, args[1]) - - -def test_get_device_registry_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - 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_device_registry( - device_manager.GetDeviceRegistryRequest(), - name='name_value', - ) - - -def test_get_device_registry_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.UpdateDeviceRegistryRequest, - dict, -]) -def test_update_device_registry_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'device_registry': {'name': 'projects/sample1/locations/sample2/registries/sample3'}} - request_init["device_registry"] = {'id': 'id_value', 'name': 'projects/sample1/locations/sample2/registries/sample3', 'event_notification_configs': [{'subfolder_matches': 'subfolder_matches_value', 'pubsub_topic_name': 'pubsub_topic_name_value'}], 'state_notification_config': {'pubsub_topic_name': 'pubsub_topic_name_value'}, 'mqtt_config': {'mqtt_enabled_state': 1}, 'http_config': {'http_enabled_state': 1}, 'log_level': 10, 'credentials': [{'public_key_certificate': {'format_': 1, 'certificate': 'certificate_value', 'x509_details': {'issuer': 'issuer_value', 'subject': 'subject_value', 'start_time': {'seconds': 751, 'nanos': 543}, 'expiry_time': {}, 'signature_algorithm': 'signature_algorithm_value', 'public_key_type': 'public_key_type_value'}}}]} - 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 = resources.DeviceRegistry( - id='id_value', - name='name_value', - log_level=resources.LogLevel.NONE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.DeviceRegistry.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_device_registry(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceRegistry) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.log_level == resources.LogLevel.NONE - - -def test_update_device_registry_rest_required_fields(request_type=device_manager.UpdateDeviceRegistryRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_device_registry._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_device_registry._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.DeviceRegistry() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = resources.DeviceRegistry.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_device_registry(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_device_registry_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_device_registry._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("deviceRegistry", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_device_registry_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_update_device_registry") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_update_device_registry") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.UpdateDeviceRegistryRequest.pb(device_manager.UpdateDeviceRegistryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.DeviceRegistry.to_json(resources.DeviceRegistry()) - - request = device_manager.UpdateDeviceRegistryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.DeviceRegistry() - - client.update_device_registry(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_device_registry_rest_bad_request(transport: str = 'rest', request_type=device_manager.UpdateDeviceRegistryRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'device_registry': {'name': 'projects/sample1/locations/sample2/registries/sample3'}} - request_init["device_registry"] = {'id': 'id_value', 'name': 'projects/sample1/locations/sample2/registries/sample3', 'event_notification_configs': [{'subfolder_matches': 'subfolder_matches_value', 'pubsub_topic_name': 'pubsub_topic_name_value'}], 'state_notification_config': {'pubsub_topic_name': 'pubsub_topic_name_value'}, 'mqtt_config': {'mqtt_enabled_state': 1}, 'http_config': {'http_enabled_state': 1}, 'log_level': 10, 'credentials': [{'public_key_certificate': {'format_': 1, 'certificate': 'certificate_value', 'x509_details': {'issuer': 'issuer_value', 'subject': 'subject_value', 'start_time': {'seconds': 751, 'nanos': 543}, 'expiry_time': {}, 'signature_algorithm': 'signature_algorithm_value', 'public_key_type': 'public_key_type_value'}}}]} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_device_registry(request) - - -def test_update_device_registry_rest_flattened(): - client = DeviceManagerClient( - 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 = resources.DeviceRegistry() - - # get arguments that satisfy an http rule for this method - sample_request = {'device_registry': {'name': 'projects/sample1/locations/sample2/registries/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - device_registry=resources.DeviceRegistry(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.DeviceRegistry.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_device_registry(**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/{device_registry.name=projects/*/locations/*/registries/*}" % client.transport._host, args[1]) - - -def test_update_device_registry_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_device_registry( - device_manager.UpdateDeviceRegistryRequest(), - device_registry=resources.DeviceRegistry(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_device_registry_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.DeleteDeviceRegistryRequest, - dict, -]) -def test_delete_device_registry_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3'} - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_device_registry(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_device_registry_rest_required_fields(request_type=device_manager.DeleteDeviceRegistryRequest): - transport_class = transports.DeviceManagerRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_device_registry._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()).delete_device_registry._get_unset_required_fields(jsonified_request) - 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 = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # 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': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_device_registry(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_device_registry_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_device_registry._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_device_registry_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "pre_delete_device_registry") as pre: - pre.assert_not_called() - pb_message = device_manager.DeleteDeviceRegistryRequest.pb(device_manager.DeleteDeviceRegistryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = device_manager.DeleteDeviceRegistryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_device_registry(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_device_registry_rest_bad_request(transport: str = 'rest', request_type=device_manager.DeleteDeviceRegistryRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_device_registry(request) - - -def test_delete_device_registry_rest_flattened(): - client = DeviceManagerClient( - 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 = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3'} - - # 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 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_device_registry(**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=projects/*/locations/*/registries/*}" % client.transport._host, args[1]) - - -def test_delete_device_registry_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - 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.delete_device_registry( - device_manager.DeleteDeviceRegistryRequest(), - name='name_value', - ) - - -def test_delete_device_registry_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.ListDeviceRegistriesRequest, - dict, -]) -def test_list_device_registries_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = device_manager.ListDeviceRegistriesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.ListDeviceRegistriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_device_registries(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeviceRegistriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_device_registries_rest_required_fields(request_type=device_manager.ListDeviceRegistriesRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_device_registries._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_device_registries._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = device_manager.ListDeviceRegistriesResponse() - # 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 - - pb_return_value = device_manager.ListDeviceRegistriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_device_registries(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_device_registries_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_device_registries._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_device_registries_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_list_device_registries") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_list_device_registries") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.ListDeviceRegistriesRequest.pb(device_manager.ListDeviceRegistriesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = device_manager.ListDeviceRegistriesResponse.to_json(device_manager.ListDeviceRegistriesResponse()) - - request = device_manager.ListDeviceRegistriesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = device_manager.ListDeviceRegistriesResponse() - - client.list_device_registries(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_device_registries_rest_bad_request(transport: str = 'rest', request_type=device_manager.ListDeviceRegistriesRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_device_registries(request) - - -def test_list_device_registries_rest_flattened(): - client = DeviceManagerClient( - 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 = device_manager.ListDeviceRegistriesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.ListDeviceRegistriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_device_registries(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/registries" % client.transport._host, args[1]) - - -def test_list_device_registries_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_device_registries( - device_manager.ListDeviceRegistriesRequest(), - parent='parent_value', - ) - - -def test_list_device_registries_rest_pager(transport: str = 'rest'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - resources.DeviceRegistry(), - resources.DeviceRegistry(), - ], - next_page_token='abc', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[], - next_page_token='def', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - ], - next_page_token='ghi', - ), - device_manager.ListDeviceRegistriesResponse( - device_registries=[ - resources.DeviceRegistry(), - resources.DeviceRegistry(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(device_manager.ListDeviceRegistriesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_device_registries(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.DeviceRegistry) - for i in results) - - pages = list(client.list_device_registries(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - device_manager.CreateDeviceRequest, - dict, -]) -def test_create_device_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - request_init["device"] = {'id': 'id_value', 'name': 'name_value', 'num_id': 636, 'credentials': [{'public_key': {'format_': 3, 'key': 'key_value'}, 'expiration_time': {'seconds': 751, 'nanos': 543}}], 'last_heartbeat_time': {}, 'last_event_time': {}, 'last_state_time': {}, 'last_config_ack_time': {}, 'last_config_send_time': {}, 'blocked': True, 'last_error_time': {}, 'last_error_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'config': {'version': 774, 'cloud_update_time': {}, 'device_ack_time': {}, 'binary_data': b'binary_data_blob'}, 'state': {'update_time': {}, 'binary_data': b'binary_data_blob'}, 'log_level': 10, 'metadata': {}, 'gateway_config': {'gateway_type': 1, 'gateway_auth_method': 1, 'last_accessed_gateway_id': 'last_accessed_gateway_id_value', 'last_accessed_gateway_time': {}}} - 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 = resources.Device( - id='id_value', - name='name_value', - num_id=636, - blocked=True, - log_level=resources.LogLevel.NONE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.Device.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_device(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Device) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.num_id == 636 - assert response.blocked is True - assert response.log_level == resources.LogLevel.NONE - - -def test_create_device_rest_required_fields(request_type=device_manager.CreateDeviceRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_device._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_device._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.Device() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = resources.Device.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_device(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_device_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_device._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "device", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_device_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_create_device") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_create_device") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.CreateDeviceRequest.pb(device_manager.CreateDeviceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.Device.to_json(resources.Device()) - - request = device_manager.CreateDeviceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Device() - - client.create_device(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_device_rest_bad_request(transport: str = 'rest', request_type=device_manager.CreateDeviceRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - request_init["device"] = {'id': 'id_value', 'name': 'name_value', 'num_id': 636, 'credentials': [{'public_key': {'format_': 3, 'key': 'key_value'}, 'expiration_time': {'seconds': 751, 'nanos': 543}}], 'last_heartbeat_time': {}, 'last_event_time': {}, 'last_state_time': {}, 'last_config_ack_time': {}, 'last_config_send_time': {}, 'blocked': True, 'last_error_time': {}, 'last_error_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'config': {'version': 774, 'cloud_update_time': {}, 'device_ack_time': {}, 'binary_data': b'binary_data_blob'}, 'state': {'update_time': {}, 'binary_data': b'binary_data_blob'}, 'log_level': 10, 'metadata': {}, 'gateway_config': {'gateway_type': 1, 'gateway_auth_method': 1, 'last_accessed_gateway_id': 'last_accessed_gateway_id_value', 'last_accessed_gateway_time': {}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_device(request) - - -def test_create_device_rest_flattened(): - client = DeviceManagerClient( - 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 = resources.Device() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - device=resources.Device(id='id_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.Device.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_device(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/registries/*}/devices" % client.transport._host, args[1]) - - -def test_create_device_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_device( - device_manager.CreateDeviceRequest(), - parent='parent_value', - device=resources.Device(id='id_value'), - ) - - -def test_create_device_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.GetDeviceRequest, - dict, -]) -def test_get_device_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - 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 = resources.Device( - id='id_value', - name='name_value', - num_id=636, - blocked=True, - log_level=resources.LogLevel.NONE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.Device.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_device(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Device) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.num_id == 636 - assert response.blocked is True - assert response.log_level == resources.LogLevel.NONE - - -def test_get_device_rest_required_fields(request_type=device_manager.GetDeviceRequest): - transport_class = transports.DeviceManagerRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_device._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_device._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("field_mask", )) - 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 = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.Device() - # 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 - - pb_return_value = resources.Device.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_device(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_device_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_device._get_unset_required_fields({}) - assert set(unset_fields) == (set(("fieldMask", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_device_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_get_device") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_get_device") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.GetDeviceRequest.pb(device_manager.GetDeviceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.Device.to_json(resources.Device()) - - request = device_manager.GetDeviceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Device() - - client.get_device(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_device_rest_bad_request(transport: str = 'rest', request_type=device_manager.GetDeviceRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_device(request) - - -def test_get_device_rest_flattened(): - client = DeviceManagerClient( - 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 = resources.Device() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - - # 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 - pb_return_value = resources.Device.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_device(**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=projects/*/locations/*/registries/*/devices/*}" % client.transport._host, args[1]) - - -def test_get_device_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - 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_device( - device_manager.GetDeviceRequest(), - name='name_value', - ) - - -def test_get_device_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.UpdateDeviceRequest, - dict, -]) -def test_update_device_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'device': {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'}} - request_init["device"] = {'id': 'id_value', 'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4', 'num_id': 636, 'credentials': [{'public_key': {'format_': 3, 'key': 'key_value'}, 'expiration_time': {'seconds': 751, 'nanos': 543}}], 'last_heartbeat_time': {}, 'last_event_time': {}, 'last_state_time': {}, 'last_config_ack_time': {}, 'last_config_send_time': {}, 'blocked': True, 'last_error_time': {}, 'last_error_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'config': {'version': 774, 'cloud_update_time': {}, 'device_ack_time': {}, 'binary_data': b'binary_data_blob'}, 'state': {'update_time': {}, 'binary_data': b'binary_data_blob'}, 'log_level': 10, 'metadata': {}, 'gateway_config': {'gateway_type': 1, 'gateway_auth_method': 1, 'last_accessed_gateway_id': 'last_accessed_gateway_id_value', 'last_accessed_gateway_time': {}}} - 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 = resources.Device( - id='id_value', - name='name_value', - num_id=636, - blocked=True, - log_level=resources.LogLevel.NONE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.Device.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_device(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Device) - assert response.id == 'id_value' - assert response.name == 'name_value' - assert response.num_id == 636 - assert response.blocked is True - assert response.log_level == resources.LogLevel.NONE - - -def test_update_device_rest_required_fields(request_type=device_manager.UpdateDeviceRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_device._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_device._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.Device() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = resources.Device.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_device(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_device_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_device._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("device", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_device_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_update_device") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_update_device") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.UpdateDeviceRequest.pb(device_manager.UpdateDeviceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.Device.to_json(resources.Device()) - - request = device_manager.UpdateDeviceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Device() - - client.update_device(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_device_rest_bad_request(transport: str = 'rest', request_type=device_manager.UpdateDeviceRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'device': {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'}} - request_init["device"] = {'id': 'id_value', 'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4', 'num_id': 636, 'credentials': [{'public_key': {'format_': 3, 'key': 'key_value'}, 'expiration_time': {'seconds': 751, 'nanos': 543}}], 'last_heartbeat_time': {}, 'last_event_time': {}, 'last_state_time': {}, 'last_config_ack_time': {}, 'last_config_send_time': {}, 'blocked': True, 'last_error_time': {}, 'last_error_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'config': {'version': 774, 'cloud_update_time': {}, 'device_ack_time': {}, 'binary_data': b'binary_data_blob'}, 'state': {'update_time': {}, 'binary_data': b'binary_data_blob'}, 'log_level': 10, 'metadata': {}, 'gateway_config': {'gateway_type': 1, 'gateway_auth_method': 1, 'last_accessed_gateway_id': 'last_accessed_gateway_id_value', 'last_accessed_gateway_time': {}}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_device(request) - - -def test_update_device_rest_flattened(): - client = DeviceManagerClient( - 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 = resources.Device() - - # get arguments that satisfy an http rule for this method - sample_request = {'device': {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - device=resources.Device(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.Device.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_device(**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/{device.name=projects/*/locations/*/registries/*/devices/*}" % client.transport._host, args[1]) - - -def test_update_device_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_device( - device_manager.UpdateDeviceRequest(), - device=resources.Device(id='id_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_device_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.DeleteDeviceRequest, - dict, -]) -def test_delete_device_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - 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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_device(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_device_rest_required_fields(request_type=device_manager.DeleteDeviceRequest): - transport_class = transports.DeviceManagerRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_device._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()).delete_device._get_unset_required_fields(jsonified_request) - 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 = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # 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': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_device(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_device_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_device._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_device_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "pre_delete_device") as pre: - pre.assert_not_called() - pb_message = device_manager.DeleteDeviceRequest.pb(device_manager.DeleteDeviceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = device_manager.DeleteDeviceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_device(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_device_rest_bad_request(transport: str = 'rest', request_type=device_manager.DeleteDeviceRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_device(request) - - -def test_delete_device_rest_flattened(): - client = DeviceManagerClient( - 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 = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - - # 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 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_device(**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=projects/*/locations/*/registries/*/devices/*}" % client.transport._host, args[1]) - - -def test_delete_device_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - 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.delete_device( - device_manager.DeleteDeviceRequest(), - name='name_value', - ) - - -def test_delete_device_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.ListDevicesRequest, - dict, -]) -def test_list_devices_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - 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 = device_manager.ListDevicesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.ListDevicesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_devices(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDevicesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_devices_rest_required_fields(request_type=device_manager.ListDevicesRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_devices._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_devices._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("device_ids", "device_num_ids", "field_mask", "gateway_list_options", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = device_manager.ListDevicesResponse() - # 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 - - pb_return_value = device_manager.ListDevicesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_devices(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_devices_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_devices._get_unset_required_fields({}) - assert set(unset_fields) == (set(("deviceIds", "deviceNumIds", "fieldMask", "gatewayListOptions", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_devices_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_list_devices") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_list_devices") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.ListDevicesRequest.pb(device_manager.ListDevicesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = device_manager.ListDevicesResponse.to_json(device_manager.ListDevicesResponse()) - - request = device_manager.ListDevicesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = device_manager.ListDevicesResponse() - - client.list_devices(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_devices_rest_bad_request(transport: str = 'rest', request_type=device_manager.ListDevicesRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_devices(request) - - -def test_list_devices_rest_flattened(): - client = DeviceManagerClient( - 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 = device_manager.ListDevicesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.ListDevicesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_devices(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/registries/*}/devices" % client.transport._host, args[1]) - - -def test_list_devices_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_devices( - device_manager.ListDevicesRequest(), - parent='parent_value', - ) - - -def test_list_devices_rest_pager(transport: str = 'rest'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - resources.Device(), - resources.Device(), - ], - next_page_token='abc', - ), - device_manager.ListDevicesResponse( - devices=[], - next_page_token='def', - ), - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - ], - next_page_token='ghi', - ), - device_manager.ListDevicesResponse( - devices=[ - resources.Device(), - resources.Device(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(device_manager.ListDevicesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - - pager = client.list_devices(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Device) - for i in results) - - pages = list(client.list_devices(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - device_manager.ModifyCloudToDeviceConfigRequest, - dict, -]) -def test_modify_cloud_to_device_config_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - 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 = resources.DeviceConfig( - version=774, - binary_data=b'binary_data_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.DeviceConfig.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.modify_cloud_to_device_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DeviceConfig) - assert response.version == 774 - assert response.binary_data == b'binary_data_blob' - - -def test_modify_cloud_to_device_config_rest_required_fields(request_type=device_manager.ModifyCloudToDeviceConfigRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request_init["name"] = "" - request_init["binary_data"] = b'' - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).modify_cloud_to_device_config._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' - jsonified_request["binaryData"] = b'binary_data_blob' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).modify_cloud_to_device_config._get_unset_required_fields(jsonified_request) - 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' - assert "binaryData" in jsonified_request - assert jsonified_request["binaryData"] == b'binary_data_blob' - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.DeviceConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = resources.DeviceConfig.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.modify_cloud_to_device_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_modify_cloud_to_device_config_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.modify_cloud_to_device_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "binaryData", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_modify_cloud_to_device_config_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_modify_cloud_to_device_config") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_modify_cloud_to_device_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.ModifyCloudToDeviceConfigRequest.pb(device_manager.ModifyCloudToDeviceConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.DeviceConfig.to_json(resources.DeviceConfig()) - - request = device_manager.ModifyCloudToDeviceConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.DeviceConfig() - - client.modify_cloud_to_device_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_modify_cloud_to_device_config_rest_bad_request(transport: str = 'rest', request_type=device_manager.ModifyCloudToDeviceConfigRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.modify_cloud_to_device_config(request) - - -def test_modify_cloud_to_device_config_rest_flattened(): - client = DeviceManagerClient( - 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 = resources.DeviceConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - binary_data=b'binary_data_blob', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.DeviceConfig.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.modify_cloud_to_device_config(**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=projects/*/locations/*/registries/*/devices/*}:modifyCloudToDeviceConfig" % client.transport._host, args[1]) - - -def test_modify_cloud_to_device_config_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - 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.modify_cloud_to_device_config( - device_manager.ModifyCloudToDeviceConfigRequest(), - name='name_value', - binary_data=b'binary_data_blob', - ) - - -def test_modify_cloud_to_device_config_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.ListDeviceConfigVersionsRequest, - dict, -]) -def test_list_device_config_versions_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - 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 = device_manager.ListDeviceConfigVersionsResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.ListDeviceConfigVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_device_config_versions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.ListDeviceConfigVersionsResponse) - - -def test_list_device_config_versions_rest_required_fields(request_type=device_manager.ListDeviceConfigVersionsRequest): - transport_class = transports.DeviceManagerRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_device_config_versions._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()).list_device_config_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("num_versions", )) - 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 = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = device_manager.ListDeviceConfigVersionsResponse() - # 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 - - pb_return_value = device_manager.ListDeviceConfigVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_device_config_versions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_device_config_versions_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_device_config_versions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("numVersions", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_device_config_versions_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_list_device_config_versions") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_list_device_config_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.ListDeviceConfigVersionsRequest.pb(device_manager.ListDeviceConfigVersionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = device_manager.ListDeviceConfigVersionsResponse.to_json(device_manager.ListDeviceConfigVersionsResponse()) - - request = device_manager.ListDeviceConfigVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = device_manager.ListDeviceConfigVersionsResponse() - - client.list_device_config_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_device_config_versions_rest_bad_request(transport: str = 'rest', request_type=device_manager.ListDeviceConfigVersionsRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_device_config_versions(request) - - -def test_list_device_config_versions_rest_flattened(): - client = DeviceManagerClient( - 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 = device_manager.ListDeviceConfigVersionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - - # 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 - pb_return_value = device_manager.ListDeviceConfigVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_device_config_versions(**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=projects/*/locations/*/registries/*/devices/*}/configVersions" % client.transport._host, args[1]) - - -def test_list_device_config_versions_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_device_config_versions( - device_manager.ListDeviceConfigVersionsRequest(), - name='name_value', - ) - - -def test_list_device_config_versions_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.ListDeviceStatesRequest, - dict, -]) -def test_list_device_states_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - 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 = device_manager.ListDeviceStatesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.ListDeviceStatesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_device_states(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.ListDeviceStatesResponse) - - -def test_list_device_states_rest_required_fields(request_type=device_manager.ListDeviceStatesRequest): - transport_class = transports.DeviceManagerRestTransport - - 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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_device_states._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()).list_device_states._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("num_states", )) - 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 = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = device_manager.ListDeviceStatesResponse() - # 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 - - pb_return_value = device_manager.ListDeviceStatesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_device_states(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_device_states_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_device_states._get_unset_required_fields({}) - assert set(unset_fields) == (set(("numStates", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_device_states_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_list_device_states") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_list_device_states") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.ListDeviceStatesRequest.pb(device_manager.ListDeviceStatesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = device_manager.ListDeviceStatesResponse.to_json(device_manager.ListDeviceStatesResponse()) - - request = device_manager.ListDeviceStatesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = device_manager.ListDeviceStatesResponse() - - client.list_device_states(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_device_states_rest_bad_request(transport: str = 'rest', request_type=device_manager.ListDeviceStatesRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_device_states(request) - - -def test_list_device_states_rest_flattened(): - client = DeviceManagerClient( - 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 = device_manager.ListDeviceStatesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - - # 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 - pb_return_value = device_manager.ListDeviceStatesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_device_states(**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=projects/*/locations/*/registries/*/devices/*}/states" % client.transport._host, args[1]) - - -def test_list_device_states_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_device_states( - device_manager.ListDeviceStatesRequest(), - name='name_value', - ) - - -def test_list_device_states_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} - 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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_set_iam_policy_rest_required_fields(request_type=iam_policy_pb2.SetIamPolicyRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # 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 - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_set_iam_policy_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.set_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "policy", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_set_iam_policy") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_set_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.SetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.set_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -def test_set_iam_policy_rest_flattened(): - client = DeviceManagerClient( - 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 = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.set_iam_policy(**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/{resource=projects/*/locations/*/registries/*}:setIamPolicy" % client.transport._host, args[1]) - - -def test_set_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_set_iam_policy_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} - 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 = policy_pb2.Policy( - version=774, - etag=b'etag_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b'etag_blob' - - -def test_get_iam_policy_rest_required_fields(request_type=iam_policy_pb2.GetIamPolicyRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request_init["resource"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_iam_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - # 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 - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_iam_policy_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_get_iam_policy") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_get_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) - - request = iam_policy_pb2.GetIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - - client.get_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -def test_get_iam_policy_rest_flattened(): - client = DeviceManagerClient( - 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 = policy_pb2.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_iam_policy(**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/{resource=projects/*/locations/*/registries/*}:getIamPolicy" % client.transport._host, args[1]) - - -def test_get_iam_policy_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_iam_policy_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} - 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 = iam_policy_pb2.TestIamPermissionsResponse( - permissions=['permissions_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ['permissions_value'] - - -def test_test_iam_permissions_rest_required_fields(request_type=iam_policy_pb2.TestIamPermissionsRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" - request = request_type(**request_init) - pb_request = request - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["resource"] = 'resource_value' - jsonified_request["permissions"] = 'permissions_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).test_iam_permissions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == 'permissions_value' - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - # 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 - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_test_iam_permissions_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("resource", "permissions", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_test_iam_permissions") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_test_iam_permissions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(iam_policy_pb2.TestIamPermissionsResponse()) - - request = iam_policy_pb2.TestIamPermissionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -def test_test_iam_permissions_rest_flattened(): - client = DeviceManagerClient( - 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 = iam_policy_pb2.TestIamPermissionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'resource': 'projects/sample1/locations/sample2/registries/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - resource='resource_value', - permissions=['permissions_value'], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.test_iam_permissions(**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/{resource=projects/*/locations/*/registries/*}:testIamPermissions" % client.transport._host, args[1]) - - -def test_test_iam_permissions_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - 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.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_test_iam_permissions_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.SendCommandToDeviceRequest, - dict, -]) -def test_send_command_to_device_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - 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 = device_manager.SendCommandToDeviceResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.SendCommandToDeviceResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.send_command_to_device(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.SendCommandToDeviceResponse) - - -def test_send_command_to_device_rest_required_fields(request_type=device_manager.SendCommandToDeviceRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request_init["name"] = "" - request_init["binary_data"] = b'' - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).send_command_to_device._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' - jsonified_request["binaryData"] = b'binary_data_blob' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).send_command_to_device._get_unset_required_fields(jsonified_request) - 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' - assert "binaryData" in jsonified_request - assert jsonified_request["binaryData"] == b'binary_data_blob' - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = device_manager.SendCommandToDeviceResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = device_manager.SendCommandToDeviceResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.send_command_to_device(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_send_command_to_device_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.send_command_to_device._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "binaryData", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_send_command_to_device_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_send_command_to_device") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_send_command_to_device") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.SendCommandToDeviceRequest.pb(device_manager.SendCommandToDeviceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = device_manager.SendCommandToDeviceResponse.to_json(device_manager.SendCommandToDeviceResponse()) - - request = device_manager.SendCommandToDeviceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = device_manager.SendCommandToDeviceResponse() - - client.send_command_to_device(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_send_command_to_device_rest_bad_request(transport: str = 'rest', request_type=device_manager.SendCommandToDeviceRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.send_command_to_device(request) - - -def test_send_command_to_device_rest_flattened(): - client = DeviceManagerClient( - 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 = device_manager.SendCommandToDeviceResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/registries/sample3/devices/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - binary_data=b'binary_data_blob', - subfolder='subfolder_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.SendCommandToDeviceResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.send_command_to_device(**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=projects/*/locations/*/registries/*/devices/*}:sendCommandToDevice" % client.transport._host, args[1]) - - -def test_send_command_to_device_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - 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.send_command_to_device( - device_manager.SendCommandToDeviceRequest(), - name='name_value', - binary_data=b'binary_data_blob', - subfolder='subfolder_value', - ) - - -def test_send_command_to_device_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.BindDeviceToGatewayRequest, - dict, -]) -def test_bind_device_to_gateway_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - 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 = device_manager.BindDeviceToGatewayResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.BindDeviceToGatewayResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.bind_device_to_gateway(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.BindDeviceToGatewayResponse) - - -def test_bind_device_to_gateway_rest_required_fields(request_type=device_manager.BindDeviceToGatewayRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["gateway_id"] = "" - request_init["device_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bind_device_to_gateway._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["gatewayId"] = 'gateway_id_value' - jsonified_request["deviceId"] = 'device_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).bind_device_to_gateway._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "gatewayId" in jsonified_request - assert jsonified_request["gatewayId"] == 'gateway_id_value' - assert "deviceId" in jsonified_request - assert jsonified_request["deviceId"] == 'device_id_value' - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = device_manager.BindDeviceToGatewayResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = device_manager.BindDeviceToGatewayResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.bind_device_to_gateway(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_bind_device_to_gateway_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.bind_device_to_gateway._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "gatewayId", "deviceId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_bind_device_to_gateway_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_bind_device_to_gateway") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_bind_device_to_gateway") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.BindDeviceToGatewayRequest.pb(device_manager.BindDeviceToGatewayRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = device_manager.BindDeviceToGatewayResponse.to_json(device_manager.BindDeviceToGatewayResponse()) - - request = device_manager.BindDeviceToGatewayRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = device_manager.BindDeviceToGatewayResponse() - - client.bind_device_to_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_bind_device_to_gateway_rest_bad_request(transport: str = 'rest', request_type=device_manager.BindDeviceToGatewayRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.bind_device_to_gateway(request) - - -def test_bind_device_to_gateway_rest_flattened(): - client = DeviceManagerClient( - 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 = device_manager.BindDeviceToGatewayResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.BindDeviceToGatewayResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.bind_device_to_gateway(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/registries/*}:bindDeviceToGateway" % client.transport._host, args[1]) - - -def test_bind_device_to_gateway_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - 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.bind_device_to_gateway( - device_manager.BindDeviceToGatewayRequest(), - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - - -def test_bind_device_to_gateway_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - device_manager.UnbindDeviceFromGatewayRequest, - dict, -]) -def test_unbind_device_from_gateway_rest(request_type): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - 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 = device_manager.UnbindDeviceFromGatewayResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.UnbindDeviceFromGatewayResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.unbind_device_from_gateway(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, device_manager.UnbindDeviceFromGatewayResponse) - - -def test_unbind_device_from_gateway_rest_required_fields(request_type=device_manager.UnbindDeviceFromGatewayRequest): - transport_class = transports.DeviceManagerRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["gateway_id"] = "" - request_init["device_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).unbind_device_from_gateway._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["gatewayId"] = 'gateway_id_value' - jsonified_request["deviceId"] = 'device_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).unbind_device_from_gateway._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "gatewayId" in jsonified_request - assert jsonified_request["gatewayId"] == 'gateway_id_value' - assert "deviceId" in jsonified_request - assert jsonified_request["deviceId"] == 'device_id_value' - - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = device_manager.UnbindDeviceFromGatewayResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = device_manager.UnbindDeviceFromGatewayResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.unbind_device_from_gateway(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_unbind_device_from_gateway_rest_unset_required_fields(): - transport = transports.DeviceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.unbind_device_from_gateway._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "gatewayId", "deviceId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_unbind_device_from_gateway_rest_interceptors(null_interceptor): - transport = transports.DeviceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeviceManagerRestInterceptor(), - ) - client = DeviceManagerClient(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.DeviceManagerRestInterceptor, "post_unbind_device_from_gateway") as post, \ - mock.patch.object(transports.DeviceManagerRestInterceptor, "pre_unbind_device_from_gateway") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = device_manager.UnbindDeviceFromGatewayRequest.pb(device_manager.UnbindDeviceFromGatewayRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = device_manager.UnbindDeviceFromGatewayResponse.to_json(device_manager.UnbindDeviceFromGatewayResponse()) - - request = device_manager.UnbindDeviceFromGatewayRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = device_manager.UnbindDeviceFromGatewayResponse() - - client.unbind_device_from_gateway(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_unbind_device_from_gateway_rest_bad_request(transport: str = 'rest', request_type=device_manager.UnbindDeviceFromGatewayRequest): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.unbind_device_from_gateway(request) - - -def test_unbind_device_from_gateway_rest_flattened(): - client = DeviceManagerClient( - 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 = device_manager.UnbindDeviceFromGatewayResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/registries/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = device_manager.UnbindDeviceFromGatewayResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.unbind_device_from_gateway(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/registries/*}:unbindDeviceFromGateway" % client.transport._host, args[1]) - - -def test_unbind_device_from_gateway_rest_flattened_error(transport: str = 'rest'): - client = DeviceManagerClient( - 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.unbind_device_from_gateway( - device_manager.UnbindDeviceFromGatewayRequest(), - parent='parent_value', - gateway_id='gateway_id_value', - device_id='device_id_value', - ) - - -def test_unbind_device_from_gateway_rest_error(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DeviceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DeviceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DeviceManagerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DeviceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DeviceManagerClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DeviceManagerClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DeviceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DeviceManagerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DeviceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DeviceManagerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DeviceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DeviceManagerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DeviceManagerGrpcTransport, - transports.DeviceManagerGrpcAsyncIOTransport, - transports.DeviceManagerRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DeviceManagerClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DeviceManagerGrpcTransport, - ) - -def test_device_manager_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DeviceManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_device_manager_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.iot_v1.services.device_manager.transports.DeviceManagerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DeviceManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_device_registry', - 'get_device_registry', - 'update_device_registry', - 'delete_device_registry', - 'list_device_registries', - 'create_device', - 'get_device', - 'update_device', - 'delete_device', - 'list_devices', - 'modify_cloud_to_device_config', - 'list_device_config_versions', - 'list_device_states', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'send_command_to_device', - 'bind_device_to_gateway', - 'unbind_device_from_gateway', - ) - 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_device_manager_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.cloud.iot_v1.services.device_manager.transports.DeviceManagerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DeviceManagerTransport( - 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', - 'https://www.googleapis.com/auth/cloudiot', -), - quota_project_id="octopus", - ) - - -def test_device_manager_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.cloud.iot_v1.services.device_manager.transports.DeviceManagerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DeviceManagerTransport() - adc.assert_called_once() - - -def test_device_manager_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) - DeviceManagerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudiot', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DeviceManagerGrpcTransport, - transports.DeviceManagerGrpcAsyncIOTransport, - ], -) -def test_device_manager_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', 'https://www.googleapis.com/auth/cloudiot',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.DeviceManagerGrpcTransport, - transports.DeviceManagerGrpcAsyncIOTransport, - transports.DeviceManagerRestTransport, - ], -) -def test_device_manager_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.DeviceManagerGrpcTransport, grpc_helpers), - (transports.DeviceManagerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_device_manager_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( - "cloudiot.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudiot', -), - scopes=["1", "2"], - default_host="cloudiot.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DeviceManagerGrpcTransport, transports.DeviceManagerGrpcAsyncIOTransport]) -def test_device_manager_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_device_manager_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.DeviceManagerRestTransport ( - 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_device_manager_host_no_port(transport_name): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudiot.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudiot.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudiot.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_device_manager_host_with_port(transport_name): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudiot.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudiot.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudiot.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_device_manager_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DeviceManagerClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DeviceManagerClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_device_registry._session - session2 = client2.transport.create_device_registry._session - assert session1 != session2 - session1 = client1.transport.get_device_registry._session - session2 = client2.transport.get_device_registry._session - assert session1 != session2 - session1 = client1.transport.update_device_registry._session - session2 = client2.transport.update_device_registry._session - assert session1 != session2 - session1 = client1.transport.delete_device_registry._session - session2 = client2.transport.delete_device_registry._session - assert session1 != session2 - session1 = client1.transport.list_device_registries._session - session2 = client2.transport.list_device_registries._session - assert session1 != session2 - session1 = client1.transport.create_device._session - session2 = client2.transport.create_device._session - assert session1 != session2 - session1 = client1.transport.get_device._session - session2 = client2.transport.get_device._session - assert session1 != session2 - session1 = client1.transport.update_device._session - session2 = client2.transport.update_device._session - assert session1 != session2 - session1 = client1.transport.delete_device._session - session2 = client2.transport.delete_device._session - assert session1 != session2 - session1 = client1.transport.list_devices._session - session2 = client2.transport.list_devices._session - assert session1 != session2 - session1 = client1.transport.modify_cloud_to_device_config._session - session2 = client2.transport.modify_cloud_to_device_config._session - assert session1 != session2 - session1 = client1.transport.list_device_config_versions._session - session2 = client2.transport.list_device_config_versions._session - assert session1 != session2 - session1 = client1.transport.list_device_states._session - session2 = client2.transport.list_device_states._session - assert session1 != session2 - session1 = client1.transport.set_iam_policy._session - session2 = client2.transport.set_iam_policy._session - assert session1 != session2 - session1 = client1.transport.get_iam_policy._session - session2 = client2.transport.get_iam_policy._session - assert session1 != session2 - session1 = client1.transport.test_iam_permissions._session - session2 = client2.transport.test_iam_permissions._session - assert session1 != session2 - session1 = client1.transport.send_command_to_device._session - session2 = client2.transport.send_command_to_device._session - assert session1 != session2 - session1 = client1.transport.bind_device_to_gateway._session - session2 = client2.transport.bind_device_to_gateway._session - assert session1 != session2 - session1 = client1.transport.unbind_device_from_gateway._session - session2 = client2.transport.unbind_device_from_gateway._session - assert session1 != session2 -def test_device_manager_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DeviceManagerGrpcTransport( - 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_device_manager_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DeviceManagerGrpcAsyncIOTransport( - 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.DeviceManagerGrpcTransport, transports.DeviceManagerGrpcAsyncIOTransport]) -def test_device_manager_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.DeviceManagerGrpcTransport, transports.DeviceManagerGrpcAsyncIOTransport]) -def test_device_manager_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_device_path(): - project = "squid" - location = "clam" - registry = "whelk" - device = "octopus" - expected = "projects/{project}/locations/{location}/registries/{registry}/devices/{device}".format(project=project, location=location, registry=registry, device=device, ) - actual = DeviceManagerClient.device_path(project, location, registry, device) - assert expected == actual - - -def test_parse_device_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "registry": "cuttlefish", - "device": "mussel", - } - path = DeviceManagerClient.device_path(**expected) - - # Check that the path construction is reversible. - actual = DeviceManagerClient.parse_device_path(path) - assert expected == actual - -def test_registry_path(): - project = "winkle" - location = "nautilus" - registry = "scallop" - expected = "projects/{project}/locations/{location}/registries/{registry}".format(project=project, location=location, registry=registry, ) - actual = DeviceManagerClient.registry_path(project, location, registry) - assert expected == actual - - -def test_parse_registry_path(): - expected = { - "project": "abalone", - "location": "squid", - "registry": "clam", - } - path = DeviceManagerClient.registry_path(**expected) - - # Check that the path construction is reversible. - actual = DeviceManagerClient.parse_registry_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DeviceManagerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = DeviceManagerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DeviceManagerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = DeviceManagerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = DeviceManagerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DeviceManagerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DeviceManagerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = DeviceManagerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DeviceManagerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = DeviceManagerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = DeviceManagerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DeviceManagerClient.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 = DeviceManagerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = DeviceManagerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DeviceManagerClient.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.DeviceManagerTransport, '_prep_wrapped_messages') as prep: - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DeviceManagerTransport, '_prep_wrapped_messages') as prep: - transport_class = DeviceManagerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DeviceManagerAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DeviceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DeviceManagerClient( - 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", [ - (DeviceManagerClient, transports.DeviceManagerGrpcTransport), - (DeviceManagerAsyncClient, transports.DeviceManagerGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - )