From ee96670bbe616517923e2e10cc1c871fa76ce1b2 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 25 Jan 2023 11:44:15 -0500 Subject: [PATCH 1/7] chore: Update gapic-generator-python to v1.8.2 (#169) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: Update gapic-generator-python to v1.8.2 PiperOrigin-RevId: 504289125 Source-Link: https://github.com/googleapis/googleapis/commit/38a48a44a44279e9cf9f2f864b588958a2d87491 Source-Link: https://github.com/googleapis/googleapis-gen/commit/b2dc22663dbe47a972c8d8c2f8a4df013dafdcbc Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjJkYzIyNjYzZGJlNDdhOTcyYzhkOGMyZjhhNGRmMDEzZGFmZGNiYyJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot --- .coveragerc | 1 + google/cloud/network_management_v1/__init__.py | 2 +- .../snippet_metadata_google.cloud.networkmanagement.v1.json | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.coveragerc b/.coveragerc index c0fc3fe..20f78aa 100644 --- a/.coveragerc +++ b/.coveragerc @@ -5,6 +5,7 @@ branch = True show_missing = True omit = google/cloud/network_management/__init__.py + google/cloud/network_management/gapic_version.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER diff --git a/google/cloud/network_management_v1/__init__.py b/google/cloud/network_management_v1/__init__.py index d807b49..e0e69e0 100644 --- a/google/cloud/network_management_v1/__init__.py +++ b/google/cloud/network_management_v1/__init__.py @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.network_management import gapic_version as package_version +from google.cloud.network_management_v1 import gapic_version as package_version __version__ = package_version.__version__ diff --git a/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json index 3c4fcff..21f4571 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-management", - "version": "1.7.1" + "version": "0.1.0" }, "snippets": [ { From 34f6c538b1914120978cbb80ba2c737b01920c66 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 30 Jan 2023 16:48:18 +0000 Subject: [PATCH 2/7] chore: fix prerelease_deps nox session [autoapprove] (#170) Source-Link: https://togithub.com/googleapis/synthtool/commit/26c7505b2f76981ec1707b851e1595c8c06e90fc Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:f946c75373c2b0040e8e318c5e85d0cf46bc6e61d0a01f3ef94d8de974ac6790 --- .github/.OwlBot.lock.yaml | 2 +- noxfile.py | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 889f77d..f0f3b24 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:c43f1d918bcf817d337aa29ff833439494a158a0831508fda4ec75dc4c0d0320 + digest: sha256:f946c75373c2b0040e8e318c5e85d0cf46bc6e61d0a01f3ef94d8de974ac6790 diff --git a/noxfile.py b/noxfile.py index e716318..95e58c5 100644 --- a/noxfile.py +++ b/noxfile.py @@ -189,9 +189,9 @@ def unit(session): def install_systemtest_dependencies(session, *constraints): # Use pre-release gRPC for system tests. - # Exclude version 1.49.0rc1 which has a known issue. - # See https://github.com/grpc/grpc/pull/30642 - session.install("--pre", "grpcio!=1.49.0rc1") + # Exclude version 1.52.0rc1 which has a known issue. + # See https://github.com/grpc/grpc/issues/32163 + session.install("--pre", "grpcio!=1.52.0rc1") session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) @@ -346,9 +346,7 @@ def prerelease_deps(session): unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES session.install(*unit_deps_all) system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS + SYSTEM_TEST_STANDARD_DEPENDENCIES + SYSTEM_TEST_EXTERNAL_DEPENDENCIES ) session.install(*system_deps_all) @@ -378,8 +376,8 @@ def prerelease_deps(session): # dependency of grpc "six", "googleapis-common-protos", - # Exclude version 1.49.0rc1 which has a known issue. See https://github.com/grpc/grpc/pull/30642 - "grpcio!=1.49.0rc1", + # Exclude version 1.52.0rc1 which has a known issue. See https://github.com/grpc/grpc/issues/32163 + "grpcio!=1.52.0rc1", "grpcio-status", "google-api-core", "proto-plus", From 16aa7af39e737cb77efddd6928a6a71506eb767f Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 8 Feb 2023 06:53:38 -0500 Subject: [PATCH 3/7] chore: Update gapic-generator-python to v1.8.4 (#171) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: Update gapic-generator-python to v1.8.4 PiperOrigin-RevId: 507808936 Source-Link: https://github.com/googleapis/googleapis/commit/64cf8492b21778ce62c66ecee81b468a293bfd4c Source-Link: https://github.com/googleapis/googleapis-gen/commit/53c48cac153d3b37f3d2c2dec4830cfd91ec4153 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNTNjNDhjYWMxNTNkM2IzN2YzZDJjMmRlYzQ4MzBjZmQ5MWVjNDE1MyJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot --- setup.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 0b1c3d9..7a101b2 100644 --- a/setup.py +++ b/setup.py @@ -57,9 +57,7 @@ if package.startswith("google") ] -namespaces = ["google"] -if "google.cloud" in packages: - namespaces.append("google.cloud") +namespaces = ["google", "google.cloud"] setuptools.setup( name=name, From 81a5df1cb5e91941f2590eec84f2d38ce2744bd2 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 8 Feb 2023 15:20:29 +0000 Subject: [PATCH 4/7] build(deps): bump cryptography from 38.0.3 to 39.0.1 in /synthtool/gcp/templates/python_library/.kokoro (#172) Source-Link: https://togithub.com/googleapis/synthtool/commit/bb171351c3946d3c3c32e60f5f18cee8c464ec51 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:f62c53736eccb0c4934a3ea9316e0d57696bb49c1a7c86c726e9bb8a2f87dadf --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/requirements.txt | 49 ++++++++++++++++++--------------------- 2 files changed, 23 insertions(+), 28 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index f0f3b24..894fb6b 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:f946c75373c2b0040e8e318c5e85d0cf46bc6e61d0a01f3ef94d8de974ac6790 + digest: sha256:f62c53736eccb0c4934a3ea9316e0d57696bb49c1a7c86c726e9bb8a2f87dadf diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 05dc467..096e480 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -113,33 +113,28 @@ commonmark==0.9.1 \ --hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \ --hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9 # via rich -cryptography==38.0.3 \ - --hash=sha256:068147f32fa662c81aebab95c74679b401b12b57494872886eb5c1139250ec5d \ - --hash=sha256:06fc3cc7b6f6cca87bd56ec80a580c88f1da5306f505876a71c8cfa7050257dd \ - --hash=sha256:25c1d1f19729fb09d42e06b4bf9895212292cb27bb50229f5aa64d039ab29146 \ - --hash=sha256:402852a0aea73833d982cabb6d0c3bb582c15483d29fb7085ef2c42bfa7e38d7 \ - --hash=sha256:4e269dcd9b102c5a3d72be3c45d8ce20377b8076a43cbed6f660a1afe365e436 \ - --hash=sha256:5419a127426084933076132d317911e3c6eb77568a1ce23c3ac1e12d111e61e0 \ - --hash=sha256:554bec92ee7d1e9d10ded2f7e92a5d70c1f74ba9524947c0ba0c850c7b011828 \ - --hash=sha256:5e89468fbd2fcd733b5899333bc54d0d06c80e04cd23d8c6f3e0542358c6060b \ - --hash=sha256:65535bc550b70bd6271984d9863a37741352b4aad6fb1b3344a54e6950249b55 \ - --hash=sha256:6ab9516b85bebe7aa83f309bacc5f44a61eeb90d0b4ec125d2d003ce41932d36 \ - --hash=sha256:6addc3b6d593cd980989261dc1cce38263c76954d758c3c94de51f1e010c9a50 \ - --hash=sha256:728f2694fa743a996d7784a6194da430f197d5c58e2f4e278612b359f455e4a2 \ - --hash=sha256:785e4056b5a8b28f05a533fab69febf5004458e20dad7e2e13a3120d8ecec75a \ - --hash=sha256:78cf5eefac2b52c10398a42765bfa981ce2372cbc0457e6bf9658f41ec3c41d8 \ - --hash=sha256:7f836217000342d448e1c9a342e9163149e45d5b5eca76a30e84503a5a96cab0 \ - --hash=sha256:8d41a46251bf0634e21fac50ffd643216ccecfaf3701a063257fe0b2be1b6548 \ - --hash=sha256:984fe150f350a3c91e84de405fe49e688aa6092b3525f407a18b9646f6612320 \ - --hash=sha256:9b24bcff7853ed18a63cfb0c2b008936a9554af24af2fb146e16d8e1aed75748 \ - --hash=sha256:b1b35d9d3a65542ed2e9d90115dfd16bbc027b3f07ee3304fc83580f26e43249 \ - --hash=sha256:b1b52c9e5f8aa2b802d48bd693190341fae201ea51c7a167d69fc48b60e8a959 \ - --hash=sha256:bbf203f1a814007ce24bd4d51362991d5cb90ba0c177a9c08825f2cc304d871f \ - --hash=sha256:be243c7e2bfcf6cc4cb350c0d5cdf15ca6383bbcb2a8ef51d3c9411a9d4386f0 \ - --hash=sha256:bfbe6ee19615b07a98b1d2287d6a6073f734735b49ee45b11324d85efc4d5cbd \ - --hash=sha256:c46837ea467ed1efea562bbeb543994c2d1f6e800785bd5a2c98bc096f5cb220 \ - --hash=sha256:dfb4f4dd568de1b6af9f4cda334adf7d72cf5bc052516e1b2608b683375dd95c \ - --hash=sha256:ed7b00096790213e09eb11c97cc6e2b757f15f3d2f85833cd2d3ec3fe37c1722 +cryptography==39.0.1 \ + --hash=sha256:0f8da300b5c8af9f98111ffd512910bc792b4c77392a9523624680f7956a99d4 \ + --hash=sha256:35f7c7d015d474f4011e859e93e789c87d21f6f4880ebdc29896a60403328f1f \ + --hash=sha256:5aa67414fcdfa22cf052e640cb5ddc461924a045cacf325cd164e65312d99502 \ + --hash=sha256:5d2d8b87a490bfcd407ed9d49093793d0f75198a35e6eb1a923ce1ee86c62b41 \ + --hash=sha256:6687ef6d0a6497e2b58e7c5b852b53f62142cfa7cd1555795758934da363a965 \ + --hash=sha256:6f8ba7f0328b79f08bdacc3e4e66fb4d7aab0c3584e0bd41328dce5262e26b2e \ + --hash=sha256:706843b48f9a3f9b9911979761c91541e3d90db1ca905fd63fee540a217698bc \ + --hash=sha256:807ce09d4434881ca3a7594733669bd834f5b2c6d5c7e36f8c00f691887042ad \ + --hash=sha256:83e17b26de248c33f3acffb922748151d71827d6021d98c70e6c1a25ddd78505 \ + --hash=sha256:96f1157a7c08b5b189b16b47bc9db2332269d6680a196341bf30046330d15388 \ + --hash=sha256:aec5a6c9864be7df2240c382740fcf3b96928c46604eaa7f3091f58b878c0bb6 \ + --hash=sha256:b0afd054cd42f3d213bf82c629efb1ee5f22eba35bf0eec88ea9ea7304f511a2 \ + --hash=sha256:ced4e447ae29ca194449a3f1ce132ded8fcab06971ef5f618605aacaa612beac \ + --hash=sha256:d1f6198ee6d9148405e49887803907fe8962a23e6c6f83ea7d98f1c0de375695 \ + --hash=sha256:e124352fd3db36a9d4a21c1aa27fd5d051e621845cb87fb851c08f4f75ce8be6 \ + --hash=sha256:e422abdec8b5fa8462aa016786680720d78bdce7a30c652b7fadf83a4ba35336 \ + --hash=sha256:ef8b72fa70b348724ff1218267e7f7375b8de4e8194d1636ee60510aae104cd0 \ + --hash=sha256:f0c64d1bd842ca2633e74a1a28033d139368ad959872533b1bab8c80e8240a0c \ + --hash=sha256:f24077a3b5298a5a06a8e0536e3ea9ec60e4c7ac486755e5fb6e6ea9b3500106 \ + --hash=sha256:fdd188c8a6ef8769f148f88f859884507b954cc64db6b52f66ef199bb9ad660a \ + --hash=sha256:fe913f20024eb2cb2f323e42a64bdf2911bb9738a15dba7d3cce48151034e3a8 # via # gcp-releasetool # secretstorage From db69894712bdc50ec543f7391bf65817e567f7e7 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 9 Feb 2023 14:11:31 -0500 Subject: [PATCH 5/7] feat: enable "rest" transport in Python for services supporting numeric enums (#173) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: enable "rest" transport in Python for services supporting numeric enums PiperOrigin-RevId: 508143576 Source-Link: https://github.com/googleapis/googleapis/commit/7a702a989db3b413f39ff8994ca53fb38b6928c2 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6ad1279c0e7aa787ac6b66c9fd4a210692edffcd Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNmFkMTI3OWMwZTdhYTc4N2FjNmI2NmM5ZmQ0YTIxMDY5MmVkZmZjZCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot --- .../network_management_v1/gapic_metadata.json | 35 + .../services/reachability_service/client.py | 2 + .../transports/__init__.py | 4 + .../reachability_service/transports/rest.py | 1034 ++++++ .../test_reachability_service.py | 2826 ++++++++++++++++- 5 files changed, 3768 insertions(+), 133 deletions(-) create mode 100644 google/cloud/network_management_v1/services/reachability_service/transports/rest.py diff --git a/google/cloud/network_management_v1/gapic_metadata.json b/google/cloud/network_management_v1/gapic_metadata.json index ee24e48..6c53154 100644 --- a/google/cloud/network_management_v1/gapic_metadata.json +++ b/google/cloud/network_management_v1/gapic_metadata.json @@ -76,6 +76,41 @@ ] } } + }, + "rest": { + "libraryClient": "ReachabilityServiceClient", + "rpcs": { + "CreateConnectivityTest": { + "methods": [ + "create_connectivity_test" + ] + }, + "DeleteConnectivityTest": { + "methods": [ + "delete_connectivity_test" + ] + }, + "GetConnectivityTest": { + "methods": [ + "get_connectivity_test" + ] + }, + "ListConnectivityTests": { + "methods": [ + "list_connectivity_tests" + ] + }, + "RerunConnectivityTest": { + "methods": [ + "rerun_connectivity_test" + ] + }, + "UpdateConnectivityTest": { + "methods": [ + "update_connectivity_test" + ] + } + } } } } diff --git a/google/cloud/network_management_v1/services/reachability_service/client.py b/google/cloud/network_management_v1/services/reachability_service/client.py index 121dc6f..b2361ef 100644 --- a/google/cloud/network_management_v1/services/reachability_service/client.py +++ b/google/cloud/network_management_v1/services/reachability_service/client.py @@ -58,6 +58,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, ReachabilityServiceTransport from .transports.grpc import ReachabilityServiceGrpcTransport from .transports.grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport +from .transports.rest import ReachabilityServiceRestTransport class ReachabilityServiceClientMeta(type): @@ -73,6 +74,7 @@ class ReachabilityServiceClientMeta(type): ) # type: Dict[str, Type[ReachabilityServiceTransport]] _transport_registry["grpc"] = ReachabilityServiceGrpcTransport _transport_registry["grpc_asyncio"] = ReachabilityServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ReachabilityServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py b/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py index 96e15b4..d61b610 100644 --- a/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py +++ b/google/cloud/network_management_v1/services/reachability_service/transports/__init__.py @@ -19,6 +19,7 @@ from .base import ReachabilityServiceTransport from .grpc import ReachabilityServiceGrpcTransport from .grpc_asyncio import ReachabilityServiceGrpcAsyncIOTransport +from .rest import ReachabilityServiceRestInterceptor, ReachabilityServiceRestTransport # Compile a registry of transports. _transport_registry = ( @@ -26,9 +27,12 @@ ) # type: Dict[str, Type[ReachabilityServiceTransport]] _transport_registry["grpc"] = ReachabilityServiceGrpcTransport _transport_registry["grpc_asyncio"] = ReachabilityServiceGrpcAsyncIOTransport +_transport_registry["rest"] = ReachabilityServiceRestTransport __all__ = ( "ReachabilityServiceTransport", "ReachabilityServiceGrpcTransport", "ReachabilityServiceGrpcAsyncIOTransport", + "ReachabilityServiceRestTransport", + "ReachabilityServiceRestInterceptor", ) diff --git a/google/cloud/network_management_v1/services/reachability_service/transports/rest.py b/google/cloud/network_management_v1/services/reachability_service/transports/rest.py new file mode 100644 index 0000000..c5209c2 --- /dev/null +++ b/google/cloud/network_management_v1/services/reachability_service/transports/rest.py @@ -0,0 +1,1034 @@ +# -*- 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 dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.network_management_v1.types import connectivity_test, reachability + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import ReachabilityServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ReachabilityServiceRestInterceptor: + """Interceptor for ReachabilityService. + + 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 ReachabilityServiceRestTransport. + + .. code-block:: python + class MyCustomReachabilityServiceInterceptor(ReachabilityServiceRestInterceptor): + def pre_create_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_connectivity_tests(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_connectivity_tests(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_rerun_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_rerun_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_connectivity_test(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_connectivity_test(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ReachabilityServiceRestTransport(interceptor=MyCustomReachabilityServiceInterceptor()) + client = ReachabilityServiceClient(transport=transport) + + + """ + + def pre_create_connectivity_test( + self, + request: reachability.CreateConnectivityTestRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reachability.CreateConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_create_connectivity_test( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_delete_connectivity_test( + self, + request: reachability.DeleteConnectivityTestRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reachability.DeleteConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_delete_connectivity_test( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_get_connectivity_test( + self, + request: reachability.GetConnectivityTestRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reachability.GetConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_get_connectivity_test( + self, response: connectivity_test.ConnectivityTest + ) -> connectivity_test.ConnectivityTest: + """Post-rpc interceptor for get_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_list_connectivity_tests( + self, + request: reachability.ListConnectivityTestsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reachability.ListConnectivityTestsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_connectivity_tests + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_list_connectivity_tests( + self, response: reachability.ListConnectivityTestsResponse + ) -> reachability.ListConnectivityTestsResponse: + """Post-rpc interceptor for list_connectivity_tests + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_rerun_connectivity_test( + self, + request: reachability.RerunConnectivityTestRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reachability.RerunConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for rerun_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_rerun_connectivity_test( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for rerun_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + def pre_update_connectivity_test( + self, + request: reachability.UpdateConnectivityTestRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reachability.UpdateConnectivityTestRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_connectivity_test + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReachabilityService server. + """ + return request, metadata + + def post_update_connectivity_test( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_connectivity_test + + Override in a subclass to manipulate the response + after it is returned by the ReachabilityService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ReachabilityServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ReachabilityServiceRestInterceptor + + +class ReachabilityServiceRestTransport(ReachabilityServiceTransport): + """REST backend transport for ReachabilityService. + + The Reachability service in the Google Cloud Network + Management API provides services that analyze the reachability + within a single Google Virtual Private Cloud (VPC) network, + between peered VPC networks, between VPC and on-premises + networks, or between VPC networks and internet hosts. A + reachability analysis is based on Google Cloud network + configurations. + + You can use the analysis results to verify these configurations + and to troubleshoot connectivity issues. + + 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 = "networkmanagement.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[ReachabilityServiceRestInterceptor] = 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 + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ReachabilityServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = {} + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateConnectivityTest(ReachabilityServiceRestStub): + def __hash__(self): + return hash("CreateConnectivityTest") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "testId": "", + } + + @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: reachability.CreateConnectivityTestRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create connectivity test method over HTTP. + + Args: + request (~.reachability.CreateConnectivityTestRequest): + The request object. Request for the ``CreateConnectivityTest`` 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/global}/connectivityTests", + "body": "resource", + }, + ] + request, metadata = self._interceptor.pre_create_connectivity_test( + request, metadata + ) + pb_request = reachability.CreateConnectivityTestRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_connectivity_test(resp) + return resp + + class _DeleteConnectivityTest(ReachabilityServiceRestStub): + def __hash__(self): + return hash("DeleteConnectivityTest") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @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: reachability.DeleteConnectivityTestRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete connectivity test method over HTTP. + + Args: + request (~.reachability.DeleteConnectivityTestRequest): + The request object. Request for the ``DeleteConnectivityTest`` 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/global/connectivityTests/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_connectivity_test( + request, metadata + ) + pb_request = reachability.DeleteConnectivityTestRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_connectivity_test(resp) + return resp + + class _GetConnectivityTest(ReachabilityServiceRestStub): + def __hash__(self): + return hash("GetConnectivityTest") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @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: reachability.GetConnectivityTestRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> connectivity_test.ConnectivityTest: + r"""Call the get connectivity test method over HTTP. + + Args: + request (~.reachability.GetConnectivityTestRequest): + The request object. Request for the ``GetConnectivityTest`` 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: + ~.connectivity_test.ConnectivityTest: + A Connectivity Test for a network + reachability analysis. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/global/connectivityTests/*}", + }, + ] + request, metadata = self._interceptor.pre_get_connectivity_test( + request, metadata + ) + pb_request = reachability.GetConnectivityTestRequest.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 = connectivity_test.ConnectivityTest() + pb_resp = connectivity_test.ConnectivityTest.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_connectivity_test(resp) + return resp + + class _ListConnectivityTests(ReachabilityServiceRestStub): + def __hash__(self): + return hash("ListConnectivityTests") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @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: reachability.ListConnectivityTestsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reachability.ListConnectivityTestsResponse: + r"""Call the list connectivity tests method over HTTP. + + Args: + request (~.reachability.ListConnectivityTestsRequest): + The request object. Request for the ``ListConnectivityTests`` 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: + ~.reachability.ListConnectivityTestsResponse: + Response for the ``ListConnectivityTests`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/global}/connectivityTests", + }, + ] + request, metadata = self._interceptor.pre_list_connectivity_tests( + request, metadata + ) + pb_request = reachability.ListConnectivityTestsRequest.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 = reachability.ListConnectivityTestsResponse() + pb_resp = reachability.ListConnectivityTestsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_connectivity_tests(resp) + return resp + + class _RerunConnectivityTest(ReachabilityServiceRestStub): + def __hash__(self): + return hash("RerunConnectivityTest") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @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: reachability.RerunConnectivityTestRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the rerun connectivity test method over HTTP. + + Args: + request (~.reachability.RerunConnectivityTestRequest): + The request object. Request for the ``RerunConnectivityTest`` 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/global/connectivityTests/*}:rerun", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_rerun_connectivity_test( + request, metadata + ) + pb_request = reachability.RerunConnectivityTestRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_rerun_connectivity_test(resp) + return resp + + class _UpdateConnectivityTest(ReachabilityServiceRestStub): + def __hash__(self): + return hash("UpdateConnectivityTest") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "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: reachability.UpdateConnectivityTestRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update connectivity test method over HTTP. + + Args: + request (~.reachability.UpdateConnectivityTestRequest): + The request object. Request for the ``UpdateConnectivityTest`` 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{resource.name=projects/*/locations/global/connectivityTests/*}", + "body": "resource", + }, + ] + request, metadata = self._interceptor.pre_update_connectivity_test( + request, metadata + ) + pb_request = reachability.UpdateConnectivityTestRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_connectivity_test(resp) + return resp + + @property + def create_connectivity_test( + self, + ) -> Callable[ + [reachability.CreateConnectivityTestRequest], operations_pb2.Operation + ]: + # 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._CreateConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_connectivity_test( + self, + ) -> Callable[ + [reachability.DeleteConnectivityTestRequest], operations_pb2.Operation + ]: + # 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._DeleteConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_connectivity_test( + self, + ) -> Callable[ + [reachability.GetConnectivityTestRequest], connectivity_test.ConnectivityTest + ]: + # 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._GetConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_connectivity_tests( + self, + ) -> Callable[ + [reachability.ListConnectivityTestsRequest], + reachability.ListConnectivityTestsResponse, + ]: + # 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._ListConnectivityTests(self._session, self._host, self._interceptor) # type: ignore + + @property + def rerun_connectivity_test( + self, + ) -> Callable[ + [reachability.RerunConnectivityTestRequest], operations_pb2.Operation + ]: + # 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._RerunConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_connectivity_test( + self, + ) -> Callable[ + [reachability.UpdateConnectivityTestRequest], operations_pb2.Operation + ]: + # 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._UpdateConnectivityTest(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ReachabilityServiceRestTransport",) diff --git a/tests/unit/gapic/network_management_v1/test_reachability_service.py b/tests/unit/gapic/network_management_v1/test_reachability_service.py index 81251e6..1ca45bc 100644 --- a/tests/unit/gapic/network_management_v1/test_reachability_service.py +++ b/tests/unit/gapic/network_management_v1/test_reachability_service.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import ( @@ -44,6 +46,7 @@ from google.protobuf import any_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore import grpc @@ -51,6 +54,8 @@ from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.network_management_v1.services.reachability_service import ( ReachabilityServiceAsyncClient, @@ -115,6 +120,7 @@ def test__get_default_mtls_endpoint(): [ (ReachabilityServiceClient, "grpc"), (ReachabilityServiceAsyncClient, "grpc_asyncio"), + (ReachabilityServiceClient, "rest"), ], ) def test_reachability_service_client_from_service_account_info( @@ -130,7 +136,11 @@ def test_reachability_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("networkmanagement.googleapis.com:443") + assert client.transport._host == ( + "networkmanagement.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkmanagement.googleapis.com" + ) @pytest.mark.parametrize( @@ -138,6 +148,7 @@ def test_reachability_service_client_from_service_account_info( [ (transports.ReachabilityServiceGrpcTransport, "grpc"), (transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ReachabilityServiceRestTransport, "rest"), ], ) def test_reachability_service_client_service_account_always_use_jwt( @@ -163,6 +174,7 @@ def test_reachability_service_client_service_account_always_use_jwt( [ (ReachabilityServiceClient, "grpc"), (ReachabilityServiceAsyncClient, "grpc_asyncio"), + (ReachabilityServiceClient, "rest"), ], ) def test_reachability_service_client_from_service_account_file( @@ -185,13 +197,18 @@ def test_reachability_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("networkmanagement.googleapis.com:443") + assert client.transport._host == ( + "networkmanagement.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkmanagement.googleapis.com" + ) def test_reachability_service_client_get_transport_class(): transport = ReachabilityServiceClient.get_transport_class() available_transports = [ transports.ReachabilityServiceGrpcTransport, + transports.ReachabilityServiceRestTransport, ] assert transport in available_transports @@ -212,6 +229,11 @@ def test_reachability_service_client_get_transport_class(): transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + ReachabilityServiceClient, + transports.ReachabilityServiceRestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -367,6 +389,18 @@ def test_reachability_service_client_client_options( "grpc_asyncio", "false", ), + ( + ReachabilityServiceClient, + transports.ReachabilityServiceRestTransport, + "rest", + "true", + ), + ( + ReachabilityServiceClient, + transports.ReachabilityServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -570,6 +604,11 @@ def test_reachability_service_client_get_mtls_endpoint_and_cert_source(client_cl transports.ReachabilityServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + ReachabilityServiceClient, + transports.ReachabilityServiceRestTransport, + "rest", + ), ], ) def test_reachability_service_client_client_options_scopes( @@ -610,6 +649,12 @@ def test_reachability_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + ReachabilityServiceClient, + transports.ReachabilityServiceRestTransport, + "rest", + None, + ), ], ) def test_reachability_service_client_client_options_credentials_file( @@ -2340,181 +2385,2618 @@ async def test_delete_connectivity_test_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + reachability.ListConnectivityTestsRequest, + dict, + ], +) +def test_list_connectivity_tests_rest(request_type): + client = ReachabilityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/global"} + 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 = reachability.ListConnectivityTestsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reachability.ListConnectivityTestsResponse.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_connectivity_tests(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConnectivityTestsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_connectivity_tests_rest_required_fields( + request_type=reachability.ListConnectivityTestsRequest, +): + transport_class = transports.ReachabilityServiceRestTransport + + 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, + ) ) - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_connectivity_tests._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_connectivity_tests._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", ) + ) + jsonified_request.update(unset_fields) - # It is an error to provide an api_key and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ReachabilityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - client_options=options, - transport=transport, - ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reachability.ListConnectivityTestsResponse() + # 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 = reachability.ListConnectivityTestsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) - # 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 = ReachabilityServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # It is an error to provide scopes and a transport instance. - transport = transports.ReachabilityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + response = client.list_connectivity_tests(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_connectivity_tests_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - with pytest.raises(ValueError): - client = ReachabilityServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + + unset_fields = transport.list_connectivity_tests._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) ) + & set(("parent",)) + ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ReachabilityServiceGrpcTransport( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_connectivity_tests_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReachabilityServiceRestInterceptor(), ) client = ReachabilityServiceClient(transport=transport) - assert client.transport is transport + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ReachabilityServiceRestInterceptor, "post_list_connectivity_tests" + ) as post, mock.patch.object( + transports.ReachabilityServiceRestInterceptor, "pre_list_connectivity_tests" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.ListConnectivityTestsRequest.pb( + reachability.ListConnectivityTestsRequest() + ) + 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 = reachability.ListConnectivityTestsResponse.to_json( + reachability.ListConnectivityTestsResponse() + ) + request = reachability.ListConnectivityTestsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reachability.ListConnectivityTestsResponse() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ReachabilityServiceGrpcTransport( + client.list_connectivity_tests( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_connectivity_tests_rest_bad_request( + transport: str = "rest", request_type=reachability.ListConnectivityTestsRequest +): + client = ReachabilityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel - transport = transports.ReachabilityServiceGrpcAsyncIOTransport( + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/global"} + 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_connectivity_tests(request) + + +def test_list_connectivity_tests_rest_flattened(): + client = ReachabilityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel + # 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 = reachability.ListConnectivityTestsResponse() -@pytest.mark.parametrize( - "transport_class", - [ - transports.ReachabilityServiceGrpcTransport, - transports.ReachabilityServiceGrpcAsyncIOTransport, - ], -) -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() + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/global"} + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - ], -) -def test_transport_kind(transport_name): - transport = ReachabilityServiceClient.get_transport_class(transport_name)( + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reachability.ListConnectivityTestsResponse.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_connectivity_tests(**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/global}/connectivityTests" + % client.transport._host, + args[1], + ) + + +def test_list_connectivity_tests_rest_flattened_error(transport: str = "rest"): + client = ReachabilityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert transport.kind == transport_name + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_connectivity_tests( + reachability.ListConnectivityTestsRequest(), + parent="parent_value", + ) -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. + +def test_list_connectivity_tests_rest_pager(transport: str = "rest"): client = ReachabilityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert isinstance( - client.transport, - transports.ReachabilityServiceGrpcTransport, - ) - -def test_reachability_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ReachabilityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + # 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 = ( + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + next_page_token="abc", + ), + reachability.ListConnectivityTestsResponse( + resources=[], + next_page_token="def", + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + ], + next_page_token="ghi", + ), + reachability.ListConnectivityTestsResponse( + resources=[ + connectivity_test.ConnectivityTest(), + connectivity_test.ConnectivityTest(), + ], + ), ) + # Two responses for two calls + response = response + response - -def test_reachability_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.ReachabilityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the values into proper Response objs + response = tuple( + reachability.ListConnectivityTestsResponse.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 - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "list_connectivity_tests", - "get_connectivity_test", - "create_connectivity_test", - "update_connectivity_test", - "rerun_connectivity_test", - "delete_connectivity_test", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + sample_request = {"parent": "projects/sample1/locations/global"} - with pytest.raises(NotImplementedError): - transport.close() + pager = client.list_connectivity_tests(request=sample_request) - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, connectivity_test.ConnectivityTest) for i in results) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + pages = list(client.list_connectivity_tests(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_reachability_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ReachabilityServiceTransport( +@pytest.mark.parametrize( + "request_type", + [ + reachability.GetConnectivityTestRequest, + dict, + ], +) +def test_get_connectivity_test_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/global/connectivityTests/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 = connectivity_test.ConnectivityTest( + name="name_value", + description="description_value", + protocol="protocol_value", + related_projects=["related_projects_value"], + display_name="display_name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = connectivity_test.ConnectivityTest.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_connectivity_test(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, connectivity_test.ConnectivityTest) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.protocol == "protocol_value" + assert response.related_projects == ["related_projects_value"] + assert response.display_name == "display_name_value" + + +def test_get_connectivity_test_rest_required_fields( + request_type=reachability.GetConnectivityTestRequest, +): + transport_class = transports.ReachabilityServiceRestTransport + + 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_connectivity_test._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_connectivity_test._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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = connectivity_test.ConnectivityTest() + # 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 = connectivity_test.ConnectivityTest.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_connectivity_test(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(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.ReachabilityServiceRestInterceptor, "post_get_connectivity_test" + ) as post, mock.patch.object( + transports.ReachabilityServiceRestInterceptor, "pre_get_connectivity_test" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.GetConnectivityTestRequest.pb( + reachability.GetConnectivityTestRequest() + ) + 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 = connectivity_test.ConnectivityTest.to_json( + connectivity_test.ConnectivityTest() + ) + + request = reachability.GetConnectivityTestRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = connectivity_test.ConnectivityTest() + + client.get_connectivity_test( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_connectivity_test_rest_bad_request( + transport: str = "rest", request_type=reachability.GetConnectivityTestRequest +): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/global/connectivityTests/sample2" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_connectivity_test(request) + + +def test_get_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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 = connectivity_test.ConnectivityTest() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/global/connectivityTests/sample2" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = connectivity_test.ConnectivityTest.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_connectivity_test(**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/global/connectivityTests/*}" + % client.transport._host, + args[1], + ) + + +def test_get_connectivity_test_rest_flattened_error(transport: str = "rest"): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.GetConnectivityTestRequest(), + name="name_value", + ) + + +def test_get_connectivity_test_rest_error(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reachability.CreateConnectivityTestRequest, + dict, + ], +) +def test_create_connectivity_test_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/global"} + request_init["resource"] = { + "name": "name_value", + "description": "description_value", + "source": { + "ip_address": "ip_address_value", + "port": 453, + "instance": "instance_value", + "gke_master_cluster": "gke_master_cluster_value", + "cloud_sql_instance": "cloud_sql_instance_value", + "network": "network_value", + "network_type": 1, + "project_id": "project_id_value", + }, + "destination": {}, + "protocol": "protocol_value", + "related_projects": ["related_projects_value1", "related_projects_value2"], + "display_name": "display_name_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "reachability_details": { + "result": 1, + "verify_time": {}, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "traces": [ + { + "endpoint_info": { + "source_ip": "source_ip_value", + "destination_ip": "destination_ip_value", + "protocol": "protocol_value", + "source_port": 1205, + "destination_port": 1734, + "source_network_uri": "source_network_uri_value", + "destination_network_uri": "destination_network_uri_value", + }, + "steps": [ + { + "description": "description_value", + "state": 1, + "causes_drop": True, + "project_id": "project_id_value", + "instance": { + "display_name": "display_name_value", + "uri": "uri_value", + "interface": "interface_value", + "network_uri": "network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + "network_tags": [ + "network_tags_value1", + "network_tags_value2", + ], + "service_account": "service_account_value", + }, + "firewall": { + "display_name": "display_name_value", + "uri": "uri_value", + "direction": "direction_value", + "action": "action_value", + "priority": 898, + "network_uri": "network_uri_value", + "target_tags": [ + "target_tags_value1", + "target_tags_value2", + ], + "target_service_accounts": [ + "target_service_accounts_value1", + "target_service_accounts_value2", + ], + "policy": "policy_value", + "firewall_rule_type": 1, + }, + "route": { + "route_type": 1, + "next_hop_type": 1, + "display_name": "display_name_value", + "uri": "uri_value", + "dest_ip_range": "dest_ip_range_value", + "next_hop": "next_hop_value", + "network_uri": "network_uri_value", + "priority": 898, + "instance_tags": [ + "instance_tags_value1", + "instance_tags_value2", + ], + }, + "endpoint": {}, + "forwarding_rule": { + "display_name": "display_name_value", + "uri": "uri_value", + "matched_protocol": "matched_protocol_value", + "matched_port_range": "matched_port_range_value", + "vip": "vip_value", + "target": "target_value", + "network_uri": "network_uri_value", + }, + "vpn_gateway": { + "display_name": "display_name_value", + "uri": "uri_value", + "network_uri": "network_uri_value", + "ip_address": "ip_address_value", + "vpn_tunnel_uri": "vpn_tunnel_uri_value", + "region": "region_value", + }, + "vpn_tunnel": { + "display_name": "display_name_value", + "uri": "uri_value", + "source_gateway": "source_gateway_value", + "remote_gateway": "remote_gateway_value", + "remote_gateway_ip": "remote_gateway_ip_value", + "source_gateway_ip": "source_gateway_ip_value", + "network_uri": "network_uri_value", + "region": "region_value", + "routing_type": 1, + }, + "deliver": { + "target": 1, + "resource_uri": "resource_uri_value", + }, + "forward": { + "target": 1, + "resource_uri": "resource_uri_value", + }, + "abort": { + "cause": 1, + "resource_uri": "resource_uri_value", + "projects_missing_permission": [ + "projects_missing_permission_value1", + "projects_missing_permission_value2", + ], + }, + "drop": {"cause": 1, "resource_uri": "resource_uri_value"}, + "load_balancer": { + "load_balancer_type": 1, + "health_check_uri": "health_check_uri_value", + "backends": [ + { + "display_name": "display_name_value", + "uri": "uri_value", + "health_check_firewall_state": 1, + "health_check_allowing_firewall_rules": [ + "health_check_allowing_firewall_rules_value1", + "health_check_allowing_firewall_rules_value2", + ], + "health_check_blocking_firewall_rules": [ + "health_check_blocking_firewall_rules_value1", + "health_check_blocking_firewall_rules_value2", + ], + } + ], + "backend_type": 1, + "backend_uri": "backend_uri_value", + }, + "network": { + "display_name": "display_name_value", + "uri": "uri_value", + "matched_ip_range": "matched_ip_range_value", + }, + "gke_master": { + "cluster_uri": "cluster_uri_value", + "cluster_network_uri": "cluster_network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + }, + "cloud_sql_instance": { + "display_name": "display_name_value", + "uri": "uri_value", + "network_uri": "network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + "region": "region_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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_connectivity_test(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_connectivity_test_rest_required_fields( + request_type=reachability.CreateConnectivityTestRequest, +): + transport_class = transports.ReachabilityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["test_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 + assert "testId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_connectivity_test._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "testId" in jsonified_request + assert jsonified_request["testId"] == request_init["test_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["testId"] = "test_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_connectivity_test._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("test_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "testId" in jsonified_request + assert jsonified_request["testId"] == "test_id_value" + + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_connectivity_test(request) + + expected_params = [ + ( + "testId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("testId",)) + & set( + ( + "parent", + "testId", + "resource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ReachabilityServiceRestInterceptor, "post_create_connectivity_test" + ) as post, mock.patch.object( + transports.ReachabilityServiceRestInterceptor, "pre_create_connectivity_test" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.CreateConnectivityTestRequest.pb( + reachability.CreateConnectivityTestRequest() + ) + 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( + operations_pb2.Operation() + ) + + request = reachability.CreateConnectivityTestRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_connectivity_test( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_connectivity_test_rest_bad_request( + transport: str = "rest", request_type=reachability.CreateConnectivityTestRequest +): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/global"} + request_init["resource"] = { + "name": "name_value", + "description": "description_value", + "source": { + "ip_address": "ip_address_value", + "port": 453, + "instance": "instance_value", + "gke_master_cluster": "gke_master_cluster_value", + "cloud_sql_instance": "cloud_sql_instance_value", + "network": "network_value", + "network_type": 1, + "project_id": "project_id_value", + }, + "destination": {}, + "protocol": "protocol_value", + "related_projects": ["related_projects_value1", "related_projects_value2"], + "display_name": "display_name_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "reachability_details": { + "result": 1, + "verify_time": {}, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "traces": [ + { + "endpoint_info": { + "source_ip": "source_ip_value", + "destination_ip": "destination_ip_value", + "protocol": "protocol_value", + "source_port": 1205, + "destination_port": 1734, + "source_network_uri": "source_network_uri_value", + "destination_network_uri": "destination_network_uri_value", + }, + "steps": [ + { + "description": "description_value", + "state": 1, + "causes_drop": True, + "project_id": "project_id_value", + "instance": { + "display_name": "display_name_value", + "uri": "uri_value", + "interface": "interface_value", + "network_uri": "network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + "network_tags": [ + "network_tags_value1", + "network_tags_value2", + ], + "service_account": "service_account_value", + }, + "firewall": { + "display_name": "display_name_value", + "uri": "uri_value", + "direction": "direction_value", + "action": "action_value", + "priority": 898, + "network_uri": "network_uri_value", + "target_tags": [ + "target_tags_value1", + "target_tags_value2", + ], + "target_service_accounts": [ + "target_service_accounts_value1", + "target_service_accounts_value2", + ], + "policy": "policy_value", + "firewall_rule_type": 1, + }, + "route": { + "route_type": 1, + "next_hop_type": 1, + "display_name": "display_name_value", + "uri": "uri_value", + "dest_ip_range": "dest_ip_range_value", + "next_hop": "next_hop_value", + "network_uri": "network_uri_value", + "priority": 898, + "instance_tags": [ + "instance_tags_value1", + "instance_tags_value2", + ], + }, + "endpoint": {}, + "forwarding_rule": { + "display_name": "display_name_value", + "uri": "uri_value", + "matched_protocol": "matched_protocol_value", + "matched_port_range": "matched_port_range_value", + "vip": "vip_value", + "target": "target_value", + "network_uri": "network_uri_value", + }, + "vpn_gateway": { + "display_name": "display_name_value", + "uri": "uri_value", + "network_uri": "network_uri_value", + "ip_address": "ip_address_value", + "vpn_tunnel_uri": "vpn_tunnel_uri_value", + "region": "region_value", + }, + "vpn_tunnel": { + "display_name": "display_name_value", + "uri": "uri_value", + "source_gateway": "source_gateway_value", + "remote_gateway": "remote_gateway_value", + "remote_gateway_ip": "remote_gateway_ip_value", + "source_gateway_ip": "source_gateway_ip_value", + "network_uri": "network_uri_value", + "region": "region_value", + "routing_type": 1, + }, + "deliver": { + "target": 1, + "resource_uri": "resource_uri_value", + }, + "forward": { + "target": 1, + "resource_uri": "resource_uri_value", + }, + "abort": { + "cause": 1, + "resource_uri": "resource_uri_value", + "projects_missing_permission": [ + "projects_missing_permission_value1", + "projects_missing_permission_value2", + ], + }, + "drop": {"cause": 1, "resource_uri": "resource_uri_value"}, + "load_balancer": { + "load_balancer_type": 1, + "health_check_uri": "health_check_uri_value", + "backends": [ + { + "display_name": "display_name_value", + "uri": "uri_value", + "health_check_firewall_state": 1, + "health_check_allowing_firewall_rules": [ + "health_check_allowing_firewall_rules_value1", + "health_check_allowing_firewall_rules_value2", + ], + "health_check_blocking_firewall_rules": [ + "health_check_blocking_firewall_rules_value1", + "health_check_blocking_firewall_rules_value2", + ], + } + ], + "backend_type": 1, + "backend_uri": "backend_uri_value", + }, + "network": { + "display_name": "display_name_value", + "uri": "uri_value", + "matched_ip_range": "matched_ip_range_value", + }, + "gke_master": { + "cluster_uri": "cluster_uri_value", + "cluster_network_uri": "cluster_network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + }, + "cloud_sql_instance": { + "display_name": "display_name_value", + "uri": "uri_value", + "network_uri": "network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + "region": "region_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_connectivity_test(request) + + +def test_create_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/global"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + test_id="test_id_value", + resource=connectivity_test.ConnectivityTest(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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_connectivity_test(**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/global}/connectivityTests" + % client.transport._host, + args[1], + ) + + +def test_create_connectivity_test_rest_flattened_error(transport: str = "rest"): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.CreateConnectivityTestRequest(), + parent="parent_value", + test_id="test_id_value", + resource=connectivity_test.ConnectivityTest(name="name_value"), + ) + + +def test_create_connectivity_test_rest_error(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reachability.UpdateConnectivityTestRequest, + dict, + ], +) +def test_update_connectivity_test_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "resource": { + "name": "projects/sample1/locations/global/connectivityTests/sample2" + } + } + request_init["resource"] = { + "name": "projects/sample1/locations/global/connectivityTests/sample2", + "description": "description_value", + "source": { + "ip_address": "ip_address_value", + "port": 453, + "instance": "instance_value", + "gke_master_cluster": "gke_master_cluster_value", + "cloud_sql_instance": "cloud_sql_instance_value", + "network": "network_value", + "network_type": 1, + "project_id": "project_id_value", + }, + "destination": {}, + "protocol": "protocol_value", + "related_projects": ["related_projects_value1", "related_projects_value2"], + "display_name": "display_name_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "reachability_details": { + "result": 1, + "verify_time": {}, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "traces": [ + { + "endpoint_info": { + "source_ip": "source_ip_value", + "destination_ip": "destination_ip_value", + "protocol": "protocol_value", + "source_port": 1205, + "destination_port": 1734, + "source_network_uri": "source_network_uri_value", + "destination_network_uri": "destination_network_uri_value", + }, + "steps": [ + { + "description": "description_value", + "state": 1, + "causes_drop": True, + "project_id": "project_id_value", + "instance": { + "display_name": "display_name_value", + "uri": "uri_value", + "interface": "interface_value", + "network_uri": "network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + "network_tags": [ + "network_tags_value1", + "network_tags_value2", + ], + "service_account": "service_account_value", + }, + "firewall": { + "display_name": "display_name_value", + "uri": "uri_value", + "direction": "direction_value", + "action": "action_value", + "priority": 898, + "network_uri": "network_uri_value", + "target_tags": [ + "target_tags_value1", + "target_tags_value2", + ], + "target_service_accounts": [ + "target_service_accounts_value1", + "target_service_accounts_value2", + ], + "policy": "policy_value", + "firewall_rule_type": 1, + }, + "route": { + "route_type": 1, + "next_hop_type": 1, + "display_name": "display_name_value", + "uri": "uri_value", + "dest_ip_range": "dest_ip_range_value", + "next_hop": "next_hop_value", + "network_uri": "network_uri_value", + "priority": 898, + "instance_tags": [ + "instance_tags_value1", + "instance_tags_value2", + ], + }, + "endpoint": {}, + "forwarding_rule": { + "display_name": "display_name_value", + "uri": "uri_value", + "matched_protocol": "matched_protocol_value", + "matched_port_range": "matched_port_range_value", + "vip": "vip_value", + "target": "target_value", + "network_uri": "network_uri_value", + }, + "vpn_gateway": { + "display_name": "display_name_value", + "uri": "uri_value", + "network_uri": "network_uri_value", + "ip_address": "ip_address_value", + "vpn_tunnel_uri": "vpn_tunnel_uri_value", + "region": "region_value", + }, + "vpn_tunnel": { + "display_name": "display_name_value", + "uri": "uri_value", + "source_gateway": "source_gateway_value", + "remote_gateway": "remote_gateway_value", + "remote_gateway_ip": "remote_gateway_ip_value", + "source_gateway_ip": "source_gateway_ip_value", + "network_uri": "network_uri_value", + "region": "region_value", + "routing_type": 1, + }, + "deliver": { + "target": 1, + "resource_uri": "resource_uri_value", + }, + "forward": { + "target": 1, + "resource_uri": "resource_uri_value", + }, + "abort": { + "cause": 1, + "resource_uri": "resource_uri_value", + "projects_missing_permission": [ + "projects_missing_permission_value1", + "projects_missing_permission_value2", + ], + }, + "drop": {"cause": 1, "resource_uri": "resource_uri_value"}, + "load_balancer": { + "load_balancer_type": 1, + "health_check_uri": "health_check_uri_value", + "backends": [ + { + "display_name": "display_name_value", + "uri": "uri_value", + "health_check_firewall_state": 1, + "health_check_allowing_firewall_rules": [ + "health_check_allowing_firewall_rules_value1", + "health_check_allowing_firewall_rules_value2", + ], + "health_check_blocking_firewall_rules": [ + "health_check_blocking_firewall_rules_value1", + "health_check_blocking_firewall_rules_value2", + ], + } + ], + "backend_type": 1, + "backend_uri": "backend_uri_value", + }, + "network": { + "display_name": "display_name_value", + "uri": "uri_value", + "matched_ip_range": "matched_ip_range_value", + }, + "gke_master": { + "cluster_uri": "cluster_uri_value", + "cluster_network_uri": "cluster_network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + }, + "cloud_sql_instance": { + "display_name": "display_name_value", + "uri": "uri_value", + "network_uri": "network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + "region": "region_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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_connectivity_test(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_connectivity_test_rest_required_fields( + request_type=reachability.UpdateConnectivityTestRequest, +): + transport_class = transports.ReachabilityServiceRestTransport + + 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_connectivity_test._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_connectivity_test._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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_connectivity_test(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "updateMask", + "resource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ReachabilityServiceRestInterceptor, "post_update_connectivity_test" + ) as post, mock.patch.object( + transports.ReachabilityServiceRestInterceptor, "pre_update_connectivity_test" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.UpdateConnectivityTestRequest.pb( + reachability.UpdateConnectivityTestRequest() + ) + 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( + operations_pb2.Operation() + ) + + request = reachability.UpdateConnectivityTestRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_connectivity_test( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_connectivity_test_rest_bad_request( + transport: str = "rest", request_type=reachability.UpdateConnectivityTestRequest +): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "resource": { + "name": "projects/sample1/locations/global/connectivityTests/sample2" + } + } + request_init["resource"] = { + "name": "projects/sample1/locations/global/connectivityTests/sample2", + "description": "description_value", + "source": { + "ip_address": "ip_address_value", + "port": 453, + "instance": "instance_value", + "gke_master_cluster": "gke_master_cluster_value", + "cloud_sql_instance": "cloud_sql_instance_value", + "network": "network_value", + "network_type": 1, + "project_id": "project_id_value", + }, + "destination": {}, + "protocol": "protocol_value", + "related_projects": ["related_projects_value1", "related_projects_value2"], + "display_name": "display_name_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "reachability_details": { + "result": 1, + "verify_time": {}, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "traces": [ + { + "endpoint_info": { + "source_ip": "source_ip_value", + "destination_ip": "destination_ip_value", + "protocol": "protocol_value", + "source_port": 1205, + "destination_port": 1734, + "source_network_uri": "source_network_uri_value", + "destination_network_uri": "destination_network_uri_value", + }, + "steps": [ + { + "description": "description_value", + "state": 1, + "causes_drop": True, + "project_id": "project_id_value", + "instance": { + "display_name": "display_name_value", + "uri": "uri_value", + "interface": "interface_value", + "network_uri": "network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + "network_tags": [ + "network_tags_value1", + "network_tags_value2", + ], + "service_account": "service_account_value", + }, + "firewall": { + "display_name": "display_name_value", + "uri": "uri_value", + "direction": "direction_value", + "action": "action_value", + "priority": 898, + "network_uri": "network_uri_value", + "target_tags": [ + "target_tags_value1", + "target_tags_value2", + ], + "target_service_accounts": [ + "target_service_accounts_value1", + "target_service_accounts_value2", + ], + "policy": "policy_value", + "firewall_rule_type": 1, + }, + "route": { + "route_type": 1, + "next_hop_type": 1, + "display_name": "display_name_value", + "uri": "uri_value", + "dest_ip_range": "dest_ip_range_value", + "next_hop": "next_hop_value", + "network_uri": "network_uri_value", + "priority": 898, + "instance_tags": [ + "instance_tags_value1", + "instance_tags_value2", + ], + }, + "endpoint": {}, + "forwarding_rule": { + "display_name": "display_name_value", + "uri": "uri_value", + "matched_protocol": "matched_protocol_value", + "matched_port_range": "matched_port_range_value", + "vip": "vip_value", + "target": "target_value", + "network_uri": "network_uri_value", + }, + "vpn_gateway": { + "display_name": "display_name_value", + "uri": "uri_value", + "network_uri": "network_uri_value", + "ip_address": "ip_address_value", + "vpn_tunnel_uri": "vpn_tunnel_uri_value", + "region": "region_value", + }, + "vpn_tunnel": { + "display_name": "display_name_value", + "uri": "uri_value", + "source_gateway": "source_gateway_value", + "remote_gateway": "remote_gateway_value", + "remote_gateway_ip": "remote_gateway_ip_value", + "source_gateway_ip": "source_gateway_ip_value", + "network_uri": "network_uri_value", + "region": "region_value", + "routing_type": 1, + }, + "deliver": { + "target": 1, + "resource_uri": "resource_uri_value", + }, + "forward": { + "target": 1, + "resource_uri": "resource_uri_value", + }, + "abort": { + "cause": 1, + "resource_uri": "resource_uri_value", + "projects_missing_permission": [ + "projects_missing_permission_value1", + "projects_missing_permission_value2", + ], + }, + "drop": {"cause": 1, "resource_uri": "resource_uri_value"}, + "load_balancer": { + "load_balancer_type": 1, + "health_check_uri": "health_check_uri_value", + "backends": [ + { + "display_name": "display_name_value", + "uri": "uri_value", + "health_check_firewall_state": 1, + "health_check_allowing_firewall_rules": [ + "health_check_allowing_firewall_rules_value1", + "health_check_allowing_firewall_rules_value2", + ], + "health_check_blocking_firewall_rules": [ + "health_check_blocking_firewall_rules_value1", + "health_check_blocking_firewall_rules_value2", + ], + } + ], + "backend_type": 1, + "backend_uri": "backend_uri_value", + }, + "network": { + "display_name": "display_name_value", + "uri": "uri_value", + "matched_ip_range": "matched_ip_range_value", + }, + "gke_master": { + "cluster_uri": "cluster_uri_value", + "cluster_network_uri": "cluster_network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + }, + "cloud_sql_instance": { + "display_name": "display_name_value", + "uri": "uri_value", + "network_uri": "network_uri_value", + "internal_ip": "internal_ip_value", + "external_ip": "external_ip_value", + "region": "region_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_connectivity_test(request) + + +def test_update_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "resource": { + "name": "projects/sample1/locations/global/connectivityTests/sample2" + } + } + + # get truthy value for each flattened field + mock_args = dict( + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + resource=connectivity_test.ConnectivityTest(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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_connectivity_test(**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.name=projects/*/locations/global/connectivityTests/*}" + % client.transport._host, + args[1], + ) + + +def test_update_connectivity_test_rest_flattened_error(transport: str = "rest"): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.UpdateConnectivityTestRequest(), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + resource=connectivity_test.ConnectivityTest(name="name_value"), + ) + + +def test_update_connectivity_test_rest_error(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reachability.RerunConnectivityTestRequest, + dict, + ], +) +def test_rerun_connectivity_test_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/global/connectivityTests/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.rerun_connectivity_test(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_rerun_connectivity_test_rest_required_fields( + request_type=reachability.RerunConnectivityTestRequest, +): + transport_class = transports.ReachabilityServiceRestTransport + + 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() + ).rerun_connectivity_test._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() + ).rerun_connectivity_test._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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.rerun_connectivity_test(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_rerun_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.rerun_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_rerun_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ReachabilityServiceRestInterceptor, "post_rerun_connectivity_test" + ) as post, mock.patch.object( + transports.ReachabilityServiceRestInterceptor, "pre_rerun_connectivity_test" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.RerunConnectivityTestRequest.pb( + reachability.RerunConnectivityTestRequest() + ) + 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( + operations_pb2.Operation() + ) + + request = reachability.RerunConnectivityTestRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.rerun_connectivity_test( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_rerun_connectivity_test_rest_bad_request( + transport: str = "rest", request_type=reachability.RerunConnectivityTestRequest +): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/global/connectivityTests/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.rerun_connectivity_test(request) + + +def test_rerun_connectivity_test_rest_error(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reachability.DeleteConnectivityTestRequest, + dict, + ], +) +def test_delete_connectivity_test_rest(request_type): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/global/connectivityTests/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_connectivity_test(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_connectivity_test_rest_required_fields( + request_type=reachability.DeleteConnectivityTestRequest, +): + transport_class = transports.ReachabilityServiceRestTransport + + 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_connectivity_test._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_connectivity_test._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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_connectivity_test(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_connectivity_test_rest_unset_required_fields(): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_connectivity_test._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_connectivity_test_rest_interceptors(null_interceptor): + transport = transports.ReachabilityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReachabilityServiceRestInterceptor(), + ) + client = ReachabilityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ReachabilityServiceRestInterceptor, "post_delete_connectivity_test" + ) as post, mock.patch.object( + transports.ReachabilityServiceRestInterceptor, "pre_delete_connectivity_test" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reachability.DeleteConnectivityTestRequest.pb( + reachability.DeleteConnectivityTestRequest() + ) + 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( + operations_pb2.Operation() + ) + + request = reachability.DeleteConnectivityTestRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_connectivity_test( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_connectivity_test_rest_bad_request( + transport: str = "rest", request_type=reachability.DeleteConnectivityTestRequest +): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/global/connectivityTests/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.delete_connectivity_test(request) + + +def test_delete_connectivity_test_rest_flattened(): + client = ReachabilityServiceClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/global/connectivityTests/sample2" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_connectivity_test(**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/global/connectivityTests/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_connectivity_test_rest_flattened_error(transport: str = "rest"): + client = ReachabilityServiceClient( + 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_connectivity_test( + reachability.DeleteConnectivityTestRequest(), + name="name_value", + ) + + +def test_delete_connectivity_test_rest_error(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + 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 = ReachabilityServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReachabilityServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ReachabilityServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReachabilityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ReachabilityServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ReachabilityServiceGrpcTransport, + transports.ReachabilityServiceGrpcAsyncIOTransport, + transports.ReachabilityServiceRestTransport, + ], +) +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 = ReachabilityServiceClient.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 = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ReachabilityServiceGrpcTransport, + ) + + +def test_reachability_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ReachabilityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_reachability_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ReachabilityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_connectivity_tests", + "get_connectivity_test", + "create_connectivity_test", + "update_connectivity_test", + "rerun_connectivity_test", + "delete_connectivity_test", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_reachability_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.network_management_v1.services.reachability_service.transports.ReachabilityServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReachabilityServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2574,6 +5056,7 @@ def test_reachability_service_transport_auth_adc(transport_class): [ transports.ReachabilityServiceGrpcTransport, transports.ReachabilityServiceGrpcAsyncIOTransport, + transports.ReachabilityServiceRestTransport, ], ) def test_reachability_service_transport_auth_gdch_credentials(transport_class): @@ -2673,11 +5156,40 @@ def test_reachability_service_grpc_transport_client_cert_source_for_mtls( ) +def test_reachability_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.ReachabilityServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_reachability_service_rest_lro_client(): + client = ReachabilityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_reachability_service_host_no_port(transport_name): @@ -2688,7 +5200,11 @@ def test_reachability_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("networkmanagement.googleapis.com:443") + assert client.transport._host == ( + "networkmanagement.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkmanagement.googleapis.com" + ) @pytest.mark.parametrize( @@ -2696,6 +5212,7 @@ def test_reachability_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_reachability_service_host_with_port(transport_name): @@ -2706,7 +5223,48 @@ def test_reachability_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("networkmanagement.googleapis.com:8000") + assert client.transport._host == ( + "networkmanagement.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networkmanagement.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_reachability_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ReachabilityServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ReachabilityServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_connectivity_tests._session + session2 = client2.transport.list_connectivity_tests._session + assert session1 != session2 + session1 = client1.transport.get_connectivity_test._session + session2 = client2.transport.get_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.create_connectivity_test._session + session2 = client2.transport.create_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.update_connectivity_test._session + session2 = client2.transport.update_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.rerun_connectivity_test._session + session2 = client2.transport.rerun_connectivity_test._session + assert session1 != session2 + session1 = client1.transport.delete_connectivity_test._session + session2 = client2.transport.delete_connectivity_test._session + assert session1 != session2 def test_reachability_service_grpc_transport_channel(): @@ -3034,6 +5592,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -3051,6 +5610,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: From 210236329e8473bd7aaa85e40f073a0447639cd3 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 17 Feb 2023 09:01:39 -0500 Subject: [PATCH 6/7] fix: Add service_yaml_parameters to py_gapic_library BUILD.bazel targets (#175) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: Add service_yaml_parameters to py_gapic_library BUILD.bazel targets PiperOrigin-RevId: 510187992 Source-Link: https://github.com/googleapis/googleapis/commit/5edc23561778df80d5293f20132765f8757a6b2c Source-Link: https://github.com/googleapis/googleapis-gen/commit/b0bedb72e4765a3e0b674a28c50ea0f9a9b26a89 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjBiZWRiNzJlNDc2NWEzZTBiNjc0YTI4YzUwZWEwZjlhOWIyNmE4OSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot --- .../reachability_service/transports/rest.py | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/google/cloud/network_management_v1/services/reachability_service/transports/rest.py b/google/cloud/network_management_v1/services/reachability_service/transports/rest.py index c5209c2..e285d85 100644 --- a/google/cloud/network_management_v1/services/reachability_service/transports/rest.py +++ b/google/cloud/network_management_v1/services/reachability_service/transports/rest.py @@ -379,7 +379,33 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: """ # Only create a new client if we do not already have one. if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = {} + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/global/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/global/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/global/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/global}/operations", + }, + ], + } rest_transport = operations_v1.OperationsRestTransport( host=self._host, From 5a5af0c6b1483f59551873823fb5962ed749121c Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 23 Feb 2023 17:07:09 -0800 Subject: [PATCH 7/7] chore(main): release 1.8.0 (#174) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 +++++++ google/cloud/network_management/gapic_version.py | 2 +- google/cloud/network_management_v1/gapic_version.py | 2 +- ...snippet_metadata_google.cloud.networkmanagement.v1.json | 2 +- 5 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d0972da..099626f 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.7.1" + ".": "1.8.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index d362f70..2dc4961 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.8.0](https://github.com/googleapis/python-network-management/compare/v1.7.1...v1.8.0) (2023-02-17) + + +### Features + +* Enable "rest" transport in Python for services supporting numeric enums ([#173](https://github.com/googleapis/python-network-management/issues/173)) ([db69894](https://github.com/googleapis/python-network-management/commit/db69894712bdc50ec543f7391bf65817e567f7e7)) + ## [1.7.1](https://github.com/googleapis/python-network-management/compare/v1.7.0...v1.7.1) (2023-01-20) diff --git a/google/cloud/network_management/gapic_version.py b/google/cloud/network_management/gapic_version.py index 84856f0..b334dcc 100644 --- a/google/cloud/network_management/gapic_version.py +++ b/google/cloud/network_management/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.7.1" # {x-release-please-version} +__version__ = "1.8.0" # {x-release-please-version} diff --git a/google/cloud/network_management_v1/gapic_version.py b/google/cloud/network_management_v1/gapic_version.py index 84856f0..b334dcc 100644 --- a/google/cloud/network_management_v1/gapic_version.py +++ b/google/cloud/network_management_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.7.1" # {x-release-please-version} +__version__ = "1.8.0" # {x-release-please-version} diff --git a/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json index 21f4571..d7fe623 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-management", - "version": "0.1.0" + "version": "1.8.0" }, "snippets": [ {