From 67751f4a12779d817bcbc846a82bc37a9d04c62c Mon Sep 17 00:00:00 2001
From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com>
Date: Fri, 6 Jan 2023 11:40:51 +0000
Subject: [PATCH 1/3] chore(python): add support for python 3.11 [autoapprove]
(#155)
Source-Link: https://togithub.com/googleapis/synthtool/commit/7197a001ffb6d8ce7b0b9b11c280f0c536c1033a
Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:c43f1d918bcf817d337aa29ff833439494a158a0831508fda4ec75dc4c0d0320
---
.github/.OwlBot.lock.yaml | 4 +-
.github/workflows/unittest.yml | 2 +-
.kokoro/samples/python3.11/common.cfg | 40 ++++++++++++++++++++
.kokoro/samples/python3.11/continuous.cfg | 6 +++
.kokoro/samples/python3.11/periodic-head.cfg | 11 ++++++
.kokoro/samples/python3.11/periodic.cfg | 6 +++
.kokoro/samples/python3.11/presubmit.cfg | 6 +++
CONTRIBUTING.rst | 6 ++-
noxfile.py | 2 +-
9 files changed, 77 insertions(+), 6 deletions(-)
create mode 100644 .kokoro/samples/python3.11/common.cfg
create mode 100644 .kokoro/samples/python3.11/continuous.cfg
create mode 100644 .kokoro/samples/python3.11/periodic-head.cfg
create mode 100644 .kokoro/samples/python3.11/periodic.cfg
create mode 100644 .kokoro/samples/python3.11/presubmit.cfg
diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml
index fccaa8e..889f77d 100644
--- a/.github/.OwlBot.lock.yaml
+++ b/.github/.OwlBot.lock.yaml
@@ -1,4 +1,4 @@
-# Copyright 2022 Google LLC
+# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -13,4 +13,4 @@
# limitations under the License.
docker:
image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest
- digest: sha256:3bf87e47c2173d7eed42714589dc4da2c07c3268610f1e47f8e1a30decbfc7f1
+ digest: sha256:c43f1d918bcf817d337aa29ff833439494a158a0831508fda4ec75dc4c0d0320
diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml
index 23000c0..8057a76 100644
--- a/.github/workflows/unittest.yml
+++ b/.github/workflows/unittest.yml
@@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- python: ['3.7', '3.8', '3.9', '3.10']
+ python: ['3.7', '3.8', '3.9', '3.10', '3.11']
steps:
- name: Checkout
uses: actions/checkout@v3
diff --git a/.kokoro/samples/python3.11/common.cfg b/.kokoro/samples/python3.11/common.cfg
new file mode 100644
index 0000000..65aeb36
--- /dev/null
+++ b/.kokoro/samples/python3.11/common.cfg
@@ -0,0 +1,40 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Build logs will be here
+action {
+ define_artifacts {
+ regex: "**/*sponge_log.xml"
+ }
+}
+
+# Specify which tests to run
+env_vars: {
+ key: "RUN_TESTS_SESSION"
+ value: "py-3.11"
+}
+
+# Declare build specific Cloud project.
+env_vars: {
+ key: "BUILD_SPECIFIC_GCLOUD_PROJECT"
+ value: "python-docs-samples-tests-311"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-network-security/.kokoro/test-samples.sh"
+}
+
+# Configure the docker image for kokoro-trampoline.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE"
+ value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker"
+}
+
+# Download secrets for samples
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples"
+
+# Download trampoline resources.
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
+
+# Use the trampoline script to run in docker.
+build_file: "python-network-security/.kokoro/trampoline_v2.sh"
\ No newline at end of file
diff --git a/.kokoro/samples/python3.11/continuous.cfg b/.kokoro/samples/python3.11/continuous.cfg
new file mode 100644
index 0000000..a1c8d97
--- /dev/null
+++ b/.kokoro/samples/python3.11/continuous.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.11/periodic-head.cfg b/.kokoro/samples/python3.11/periodic-head.cfg
new file mode 100644
index 0000000..7fe442b
--- /dev/null
+++ b/.kokoro/samples/python3.11/periodic-head.cfg
@@ -0,0 +1,11 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-network-security/.kokoro/test-samples-against-head.sh"
+}
diff --git a/.kokoro/samples/python3.11/periodic.cfg b/.kokoro/samples/python3.11/periodic.cfg
new file mode 100644
index 0000000..71cd1e5
--- /dev/null
+++ b/.kokoro/samples/python3.11/periodic.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "False"
+}
diff --git a/.kokoro/samples/python3.11/presubmit.cfg b/.kokoro/samples/python3.11/presubmit.cfg
new file mode 100644
index 0000000..a1c8d97
--- /dev/null
+++ b/.kokoro/samples/python3.11/presubmit.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst
index 991aa93..2ddc579 100644
--- a/CONTRIBUTING.rst
+++ b/CONTRIBUTING.rst
@@ -22,7 +22,7 @@ In order to add a feature:
documentation.
- The feature must work fully on the following CPython versions:
- 3.7, 3.8, 3.9 and 3.10 on both UNIX and Windows.
+ 3.7, 3.8, 3.9, 3.10 and 3.11 on both UNIX and Windows.
- The feature must not add unnecessary dependencies (where
"unnecessary" is of course subjective, but new dependencies should
@@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests.
- To run a single unit test::
- $ nox -s unit-3.10 -- -k
+ $ nox -s unit-3.11 -- -k
.. note::
@@ -225,11 +225,13 @@ We support:
- `Python 3.8`_
- `Python 3.9`_
- `Python 3.10`_
+- `Python 3.11`_
.. _Python 3.7: https://docs.python.org/3.7/
.. _Python 3.8: https://docs.python.org/3.8/
.. _Python 3.9: https://docs.python.org/3.9/
.. _Python 3.10: https://docs.python.org/3.10/
+.. _Python 3.11: https://docs.python.org/3.11/
Supported versions can be found in our ``noxfile.py`` `config`_.
diff --git a/noxfile.py b/noxfile.py
index d8440c0..e716318 100644
--- a/noxfile.py
+++ b/noxfile.py
@@ -32,7 +32,7 @@
DEFAULT_PYTHON_VERSION = "3.8"
-UNIT_TEST_PYTHON_VERSIONS = ["3.7", "3.8", "3.9", "3.10"]
+UNIT_TEST_PYTHON_VERSIONS = ["3.7", "3.8", "3.9", "3.10", "3.11"]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
From 5233d61f1c31da18125844e8059e7bb8e157150c Mon Sep 17 00:00:00 2001
From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com>
Date: Mon, 9 Jan 2023 23:20:21 -0500
Subject: [PATCH 2/3] feat: Add support for python 3.11 (#156)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* feat: Add support for python 3.11
chore: Update gapic-generator-python to v1.8.0
PiperOrigin-RevId: 500768693
Source-Link: https://github.com/googleapis/googleapis/commit/190b612e3d0ff8f025875a669e5d68a1446d43c1
Source-Link: https://github.com/googleapis/googleapis-gen/commit/7bf29a414b9ecac3170f0b65bdc2a95705c0ef1a
Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiN2JmMjlhNDE0YjllY2FjMzE3MGYwYjY1YmRjMmE5NTcwNWMwZWYxYSJ9
* 🦉 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
---
.../services/network_security/async_client.py | 2 +-
.../services/network_security/client.py | 2 +-
.../gapic_metadata.json | 80 -
.../services/network_security/async_client.py | 2 +-
.../services/network_security/client.py | 4 +-
.../network_security/transports/__init__.py | 4 -
...adata_google.cloud.networksecurity.v1.json | 2 +-
..._google.cloud.networksecurity.v1beta1.json | 2 +-
testing/constraints-3.12.txt | 6 +
.../test_network_security.py | 6521 ++---------------
10 files changed, 599 insertions(+), 6026 deletions(-)
create mode 100644 testing/constraints-3.12.txt
diff --git a/google/cloud/network_security_v1/services/network_security/async_client.py b/google/cloud/network_security_v1/services/network_security/async_client.py
index b07981a..cf13e3b 100644
--- a/google/cloud/network_security_v1/services/network_security/async_client.py
+++ b/google/cloud/network_security_v1/services/network_security/async_client.py
@@ -168,7 +168,7 @@ def get_mtls_endpoint_and_cert_source(
The API endpoint is determined in the following order:
(1) if `client_options.api_endpoint` if provided, use the provided one.
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
- default mTLS endpoint; if the environment variabel is "never", use the default API
+ default mTLS endpoint; if the environment variable is "never", use the default API
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
use the default API endpoint.
diff --git a/google/cloud/network_security_v1/services/network_security/client.py b/google/cloud/network_security_v1/services/network_security/client.py
index fd8793b..40361d9 100644
--- a/google/cloud/network_security_v1/services/network_security/client.py
+++ b/google/cloud/network_security_v1/services/network_security/client.py
@@ -358,7 +358,7 @@ def get_mtls_endpoint_and_cert_source(
The API endpoint is determined in the following order:
(1) if `client_options.api_endpoint` if provided, use the provided one.
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
- default mTLS endpoint; if the environment variabel is "never", use the default API
+ default mTLS endpoint; if the environment variable is "never", use the default API
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
use the default API endpoint.
diff --git a/google/cloud/network_security_v1beta1/gapic_metadata.json b/google/cloud/network_security_v1beta1/gapic_metadata.json
index 9b081e3..8bf9dac 100644
--- a/google/cloud/network_security_v1beta1/gapic_metadata.json
+++ b/google/cloud/network_security_v1beta1/gapic_metadata.json
@@ -166,86 +166,6 @@
]
}
}
- },
- "rest": {
- "libraryClient": "NetworkSecurityClient",
- "rpcs": {
- "CreateAuthorizationPolicy": {
- "methods": [
- "create_authorization_policy"
- ]
- },
- "CreateClientTlsPolicy": {
- "methods": [
- "create_client_tls_policy"
- ]
- },
- "CreateServerTlsPolicy": {
- "methods": [
- "create_server_tls_policy"
- ]
- },
- "DeleteAuthorizationPolicy": {
- "methods": [
- "delete_authorization_policy"
- ]
- },
- "DeleteClientTlsPolicy": {
- "methods": [
- "delete_client_tls_policy"
- ]
- },
- "DeleteServerTlsPolicy": {
- "methods": [
- "delete_server_tls_policy"
- ]
- },
- "GetAuthorizationPolicy": {
- "methods": [
- "get_authorization_policy"
- ]
- },
- "GetClientTlsPolicy": {
- "methods": [
- "get_client_tls_policy"
- ]
- },
- "GetServerTlsPolicy": {
- "methods": [
- "get_server_tls_policy"
- ]
- },
- "ListAuthorizationPolicies": {
- "methods": [
- "list_authorization_policies"
- ]
- },
- "ListClientTlsPolicies": {
- "methods": [
- "list_client_tls_policies"
- ]
- },
- "ListServerTlsPolicies": {
- "methods": [
- "list_server_tls_policies"
- ]
- },
- "UpdateAuthorizationPolicy": {
- "methods": [
- "update_authorization_policy"
- ]
- },
- "UpdateClientTlsPolicy": {
- "methods": [
- "update_client_tls_policy"
- ]
- },
- "UpdateServerTlsPolicy": {
- "methods": [
- "update_server_tls_policy"
- ]
- }
- }
}
}
}
diff --git a/google/cloud/network_security_v1beta1/services/network_security/async_client.py b/google/cloud/network_security_v1beta1/services/network_security/async_client.py
index ef408cd..ab9236c 100644
--- a/google/cloud/network_security_v1beta1/services/network_security/async_client.py
+++ b/google/cloud/network_security_v1beta1/services/network_security/async_client.py
@@ -172,7 +172,7 @@ def get_mtls_endpoint_and_cert_source(
The API endpoint is determined in the following order:
(1) if `client_options.api_endpoint` if provided, use the provided one.
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
- default mTLS endpoint; if the environment variabel is "never", use the default API
+ default mTLS endpoint; if the environment variable is "never", use the default API
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
use the default API endpoint.
diff --git a/google/cloud/network_security_v1beta1/services/network_security/client.py b/google/cloud/network_security_v1beta1/services/network_security/client.py
index 10c6d31..2024721 100644
--- a/google/cloud/network_security_v1beta1/services/network_security/client.py
+++ b/google/cloud/network_security_v1beta1/services/network_security/client.py
@@ -75,7 +75,6 @@
from .transports.base import DEFAULT_CLIENT_INFO, NetworkSecurityTransport
from .transports.grpc import NetworkSecurityGrpcTransport
from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport
-from .transports.rest import NetworkSecurityRestTransport
class NetworkSecurityClientMeta(type):
@@ -91,7 +90,6 @@ class NetworkSecurityClientMeta(type):
) # type: Dict[str, Type[NetworkSecurityTransport]]
_transport_registry["grpc"] = NetworkSecurityGrpcTransport
_transport_registry["grpc_asyncio"] = NetworkSecurityGrpcAsyncIOTransport
- _transport_registry["rest"] = NetworkSecurityRestTransport
def get_transport_class(
cls,
@@ -362,7 +360,7 @@ def get_mtls_endpoint_and_cert_source(
The API endpoint is determined in the following order:
(1) if `client_options.api_endpoint` if provided, use the provided one.
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
- default mTLS endpoint; if the environment variabel is "never", use the default API
+ default mTLS endpoint; if the environment variable is "never", use the default API
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
use the default API endpoint.
diff --git a/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py b/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py
index 4814e0c..e6f7341 100644
--- a/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py
+++ b/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py
@@ -19,18 +19,14 @@
from .base import NetworkSecurityTransport
from .grpc import NetworkSecurityGrpcTransport
from .grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport
-from .rest import NetworkSecurityRestInterceptor, NetworkSecurityRestTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[NetworkSecurityTransport]]
_transport_registry["grpc"] = NetworkSecurityGrpcTransport
_transport_registry["grpc_asyncio"] = NetworkSecurityGrpcAsyncIOTransport
-_transport_registry["rest"] = NetworkSecurityRestTransport
__all__ = (
"NetworkSecurityTransport",
"NetworkSecurityGrpcTransport",
"NetworkSecurityGrpcAsyncIOTransport",
- "NetworkSecurityRestTransport",
- "NetworkSecurityRestInterceptor",
)
diff --git a/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json
index ac7698f..0bc5339 100644
--- a/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json
+++ b/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-network-security",
- "version": "0.8.0"
+ "version": "0.1.0"
},
"snippets": [
{
diff --git a/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json
index 9310c4a..fd7e421 100644
--- a/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json
+++ b/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-network-security",
- "version": "0.8.0"
+ "version": "0.1.0"
},
"snippets": [
{
diff --git a/testing/constraints-3.12.txt b/testing/constraints-3.12.txt
new file mode 100644
index 0000000..ed7f9ae
--- /dev/null
+++ b/testing/constraints-3.12.txt
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+# This constraints file is required for unit tests.
+# List all library dependencies and extras in this file.
+google-api-core
+proto-plus
+protobuf
diff --git a/tests/unit/gapic/network_security_v1beta1/test_network_security.py b/tests/unit/gapic/network_security_v1beta1/test_network_security.py
index 6b8a98b..db322e0 100644
--- a/tests/unit/gapic/network_security_v1beta1/test_network_security.py
+++ b/tests/unit/gapic/network_security_v1beta1/test_network_security.py
@@ -22,8 +22,6 @@
except ImportError: # pragma: NO COVER
import mock
-from collections.abc import Iterable
-import json
import math
from google.api_core import (
@@ -49,15 +47,12 @@
from google.oauth2 import service_account
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
import grpc
from grpc.experimental import aio
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_security_v1beta1.services.network_security import (
NetworkSecurityAsyncClient,
@@ -130,7 +125,6 @@ def test__get_default_mtls_endpoint():
[
(NetworkSecurityClient, "grpc"),
(NetworkSecurityAsyncClient, "grpc_asyncio"),
- (NetworkSecurityClient, "rest"),
],
)
def test_network_security_client_from_service_account_info(
@@ -146,11 +140,7 @@ def test_network_security_client_from_service_account_info(
assert client.transport._credentials == creds
assert isinstance(client, client_class)
- assert client.transport._host == (
- "networksecurity.googleapis.com:443"
- if transport_name in ["grpc", "grpc_asyncio"]
- else "https://networksecurity.googleapis.com"
- )
+ assert client.transport._host == ("networksecurity.googleapis.com:443")
@pytest.mark.parametrize(
@@ -158,7 +148,6 @@ def test_network_security_client_from_service_account_info(
[
(transports.NetworkSecurityGrpcTransport, "grpc"),
(transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"),
- (transports.NetworkSecurityRestTransport, "rest"),
],
)
def test_network_security_client_service_account_always_use_jwt(
@@ -184,7 +173,6 @@ def test_network_security_client_service_account_always_use_jwt(
[
(NetworkSecurityClient, "grpc"),
(NetworkSecurityAsyncClient, "grpc_asyncio"),
- (NetworkSecurityClient, "rest"),
],
)
def test_network_security_client_from_service_account_file(
@@ -207,18 +195,13 @@ def test_network_security_client_from_service_account_file(
assert client.transport._credentials == creds
assert isinstance(client, client_class)
- assert client.transport._host == (
- "networksecurity.googleapis.com:443"
- if transport_name in ["grpc", "grpc_asyncio"]
- else "https://networksecurity.googleapis.com"
- )
+ assert client.transport._host == ("networksecurity.googleapis.com:443")
def test_network_security_client_get_transport_class():
transport = NetworkSecurityClient.get_transport_class()
available_transports = [
transports.NetworkSecurityGrpcTransport,
- transports.NetworkSecurityRestTransport,
]
assert transport in available_transports
@@ -235,7 +218,6 @@ def test_network_security_client_get_transport_class():
transports.NetworkSecurityGrpcAsyncIOTransport,
"grpc_asyncio",
),
- (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"),
],
)
@mock.patch.object(
@@ -391,18 +373,6 @@ def test_network_security_client_client_options(
"grpc_asyncio",
"false",
),
- (
- NetworkSecurityClient,
- transports.NetworkSecurityRestTransport,
- "rest",
- "true",
- ),
- (
- NetworkSecurityClient,
- transports.NetworkSecurityRestTransport,
- "rest",
- "false",
- ),
],
)
@mock.patch.object(
@@ -602,7 +572,6 @@ def test_network_security_client_get_mtls_endpoint_and_cert_source(client_class)
transports.NetworkSecurityGrpcAsyncIOTransport,
"grpc_asyncio",
),
- (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"),
],
)
def test_network_security_client_client_options_scopes(
@@ -643,7 +612,6 @@ def test_network_security_client_client_options_scopes(
"grpc_asyncio",
grpc_helpers_async,
),
- (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", None),
],
)
def test_network_security_client_client_options_credentials_file(
@@ -5129,6086 +5097,773 @@ async def test_delete_client_tls_policy_flattened_error_async():
)
-@pytest.mark.parametrize(
- "request_type",
- [
- authorization_policy.ListAuthorizationPoliciesRequest,
- dict,
- ],
-)
-def test_list_authorization_policies_rest(request_type):
- client = NetworkSecurityClient(
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.NetworkSecurityGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = authorization_policy.ListAuthorizationPoliciesResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = authorization_policy.ListAuthorizationPoliciesResponse.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_authorization_policies(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListAuthorizationPoliciesPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-def test_list_authorization_policies_rest_required_fields(
- request_type=authorization_policy.ListAuthorizationPoliciesRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(
- pb_request,
- including_default_value_fields=False,
- use_integers_for_enums=False,
- )
)
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).list_authorization_policies._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_authorization_policies._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(
- (
- "page_size",
- "page_token",
+ with pytest.raises(ValueError):
+ client = NetworkSecurityClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- )
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
- client = NetworkSecurityClient(
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.NetworkSecurityGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = authorization_policy.ListAuthorizationPoliciesResponse()
- # 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 = authorization_policy.ListAuthorizationPoliciesResponse.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_authorization_policies(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_list_authorization_policies_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
)
-
- unset_fields = transport.list_authorization_policies._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(
- (
- "pageSize",
- "pageToken",
- )
+ with pytest.raises(ValueError):
+ client = NetworkSecurityClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
)
- & set(("parent",))
- )
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_authorization_policies_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.NetworkSecurityGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
)
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_list_authorization_policies"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_list_authorization_policies"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = authorization_policy.ListAuthorizationPoliciesRequest.pb(
- authorization_policy.ListAuthorizationPoliciesRequest()
- )
- 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 = (
- authorization_policy.ListAuthorizationPoliciesResponse.to_json(
- authorization_policy.ListAuthorizationPoliciesResponse()
- )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = NetworkSecurityClient(
+ client_options=options,
+ transport=transport,
)
- request = authorization_policy.ListAuthorizationPoliciesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = authorization_policy.ListAuthorizationPoliciesResponse()
-
- client.list_authorization_policies(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+ # 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 = NetworkSecurityClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
)
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_list_authorization_policies_rest_bad_request(
- transport: str = "rest",
- request_type=authorization_policy.ListAuthorizationPoliciesRequest,
-):
- client = NetworkSecurityClient(
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.NetworkSecurityGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
)
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_authorization_policies(request)
+ with pytest.raises(ValueError):
+ client = NetworkSecurityClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
-def test_list_authorization_policies_rest_flattened():
- client = NetworkSecurityClient(
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.NetworkSecurityGrpcTransport(
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 = authorization_policy.ListAuthorizationPoliciesResponse()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {"parent": "projects/sample1/locations/sample2"}
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = authorization_policy.ListAuthorizationPoliciesResponse.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_authorization_policies(**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/v1beta1/{parent=projects/*/locations/*}/authorizationPolicies"
- % client.transport._host,
- args[1],
- )
+ client = NetworkSecurityClient(transport=transport)
+ assert client.transport is transport
-def test_list_authorization_policies_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.NetworkSecurityGrpcTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
)
+ channel = transport.grpc_channel
+ assert channel
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.list_authorization_policies(
- authorization_policy.ListAuthorizationPoliciesRequest(),
- parent="parent_value",
- )
-
-
-def test_list_authorization_policies_rest_pager(transport: str = "rest"):
- client = NetworkSecurityClient(
+ transport = transports.NetworkSecurityGrpcAsyncIOTransport(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
)
+ channel = transport.grpc_channel
+ assert channel
- # 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 = (
- authorization_policy.ListAuthorizationPoliciesResponse(
- authorization_policies=[
- authorization_policy.AuthorizationPolicy(),
- authorization_policy.AuthorizationPolicy(),
- authorization_policy.AuthorizationPolicy(),
- ],
- next_page_token="abc",
- ),
- authorization_policy.ListAuthorizationPoliciesResponse(
- authorization_policies=[],
- next_page_token="def",
- ),
- authorization_policy.ListAuthorizationPoliciesResponse(
- authorization_policies=[
- authorization_policy.AuthorizationPolicy(),
- ],
- next_page_token="ghi",
- ),
- authorization_policy.ListAuthorizationPoliciesResponse(
- authorization_policies=[
- authorization_policy.AuthorizationPolicy(),
- authorization_policy.AuthorizationPolicy(),
- ],
- ),
- )
- # Two responses for two calls
- response = response + response
-
- # Wrap the values into proper Response objs
- response = tuple(
- authorization_policy.ListAuthorizationPoliciesResponse.to_json(x)
- for x in response
- )
- return_values = tuple(Response() for i in response)
- for return_val, response_val in zip(return_values, response):
- return_val._content = response_val.encode("UTF-8")
- return_val.status_code = 200
- req.side_effect = return_values
-
- sample_request = {"parent": "projects/sample1/locations/sample2"}
-
- pager = client.list_authorization_policies(request=sample_request)
-
- results = list(pager)
- assert len(results) == 6
- assert all(
- isinstance(i, authorization_policy.AuthorizationPolicy) for i in results
- )
- pages = list(client.list_authorization_policies(request=sample_request).pages)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.NetworkSecurityGrpcTransport,
+ transports.NetworkSecurityGrpcAsyncIOTransport,
+ ],
+)
+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(
- "request_type",
+ "transport_name",
[
- authorization_policy.GetAuthorizationPolicyRequest,
- dict,
+ "grpc",
],
)
-def test_get_authorization_policy_rest(request_type):
- client = NetworkSecurityClient(
+def test_transport_kind(transport_name):
+ transport = NetworkSecurityClient.get_transport_class(transport_name)(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = authorization_policy.AuthorizationPolicy(
- name="name_value",
- description="description_value",
- action=authorization_policy.AuthorizationPolicy.Action.ALLOW,
- )
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = authorization_policy.AuthorizationPolicy.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_authorization_policy(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, authorization_policy.AuthorizationPolicy)
- assert response.name == "name_value"
- assert response.description == "description_value"
- assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW
-
-
-def test_get_authorization_policy_rest_required_fields(
- request_type=authorization_policy.GetAuthorizationPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- 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,
- )
)
+ assert transport.kind == transport_name
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).get_authorization_policy._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_authorization_policy._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"
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
client = NetworkSecurityClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = authorization_policy.AuthorizationPolicy()
- # 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 = authorization_policy.AuthorizationPolicy.pb(return_value)
- json_return_value = json_format.MessageToJson(pb_return_value)
+ )
+ assert isinstance(
+ client.transport,
+ transports.NetworkSecurityGrpcTransport,
+ )
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.get_authorization_policy(request)
+def test_network_security_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
+ transport = transports.NetworkSecurityTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-def test_get_authorization_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.get_authorization_policy._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_authorization_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_get_authorization_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_get_authorization_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = authorization_policy.GetAuthorizationPolicyRequest.pb(
- authorization_policy.GetAuthorizationPolicyRequest()
- )
- 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 = authorization_policy.AuthorizationPolicy.to_json(
- authorization_policy.AuthorizationPolicy()
- )
-
- request = authorization_policy.GetAuthorizationPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = authorization_policy.AuthorizationPolicy()
-
- client.get_authorization_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
+def test_network_security_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.network_security_v1beta1.services.network_security.transports.NetworkSecurityTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.NetworkSecurityTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
)
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_authorization_policy_rest_bad_request(
- transport: str = "rest",
- request_type=authorization_policy.GetAuthorizationPolicyRequest,
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "list_authorization_policies",
+ "get_authorization_policy",
+ "create_authorization_policy",
+ "update_authorization_policy",
+ "delete_authorization_policy",
+ "list_server_tls_policies",
+ "get_server_tls_policy",
+ "create_server_tls_policy",
+ "update_server_tls_policy",
+ "delete_server_tls_policy",
+ "list_client_tls_policies",
+ "get_client_tls_policy",
+ "create_client_tls_policy",
+ "update_client_tls_policy",
+ "delete_client_tls_policy",
+ "set_iam_policy",
+ "get_iam_policy",
+ "test_iam_permissions",
+ "get_location",
+ "list_locations",
+ "get_operation",
+ "cancel_operation",
+ "delete_operation",
+ "list_operations",
)
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_authorization_policy(request)
-
+ with pytest.raises(NotImplementedError):
+ transport.close()
-def test_get_authorization_policy_rest_flattened():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
- # 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 = authorization_policy.AuthorizationPolicy()
+ # Catch all for all remaining methods and properties
+ remainder = [
+ "kind",
+ ]
+ for r in remainder:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, r)()
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- }
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
+def test_network_security_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_security_v1beta1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.NetworkSecurityTransport(
+ credentials_file="credentials.json",
+ quota_project_id="octopus",
)
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = authorization_policy.AuthorizationPolicy.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_authorization_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{name=projects/*/locations/*/authorizationPolicies/*}"
- % client.transport._host,
- args[1],
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ quota_project_id="octopus",
)
-def test_get_authorization_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_authorization_policy(
- authorization_policy.GetAuthorizationPolicyRequest(),
- name="name_value",
- )
+def test_network_security_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
+ "google.cloud.network_security_v1beta1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.NetworkSecurityTransport()
+ adc.assert_called_once()
-def test_get_authorization_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
+def test_network_security_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ NetworkSecurityClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ quota_project_id=None,
+ )
@pytest.mark.parametrize(
- "request_type",
+ "transport_class",
[
- gcn_authorization_policy.CreateAuthorizationPolicyRequest,
- dict,
+ transports.NetworkSecurityGrpcTransport,
+ transports.NetworkSecurityGrpcAsyncIOTransport,
],
)
-def test_create_authorization_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request_init["authorization_policy"] = {
- "name": "name_value",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "action": 1,
- "rules": [
- {
- "sources": [
- {
- "principals": ["principals_value1", "principals_value2"],
- "ip_blocks": ["ip_blocks_value1", "ip_blocks_value2"],
- }
- ],
- "destinations": [
- {
- "hosts": ["hosts_value1", "hosts_value2"],
- "ports": [569, 570],
- "methods": ["methods_value1", "methods_value2"],
- "http_header_match": {
- "regex_match": "regex_match_value",
- "header_name": "header_name_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_authorization_policy(request)
-
- # Establish that the response is the type that we expect.
- assert response.operation.name == "operations/spam"
-
-
-def test_create_authorization_policy_rest_required_fields(
- request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request_init["authorization_policy_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,
+def test_network_security_transport_auth_adc(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ quota_project_id="octopus",
)
- )
-
- # verify fields with default values are dropped
- assert "authorizationPolicyId" not in jsonified_request
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_authorization_policy._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
- assert "authorizationPolicyId" in jsonified_request
- assert (
- jsonified_request["authorizationPolicyId"]
- == request_init["authorization_policy_id"]
- )
-
- jsonified_request["parent"] = "parent_value"
- jsonified_request["authorizationPolicyId"] = "authorization_policy_id_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_authorization_policy._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("authorization_policy_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 "authorizationPolicyId" in jsonified_request
- assert jsonified_request["authorizationPolicyId"] == "authorization_policy_id_value"
-
- client = NetworkSecurityClient(
- 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_authorization_policy(request)
-
- expected_params = [
- (
- "authorizationPolicyId",
- "",
- ),
- ("$alt", "json;enum-encoding=int"),
- ]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_create_authorization_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.create_authorization_policy._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(("authorizationPolicyId",))
- & set(
- (
- "parent",
- "authorizationPolicyId",
- "authorizationPolicy",
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.NetworkSecurityGrpcTransport,
+ transports.NetworkSecurityGrpcAsyncIOTransport,
+ ],
+)
+def test_network_security_transport_auth_gdch_credentials(transport_class):
+ host = "https://language.com"
+ api_audience_tests = [None, "https://language2.com"]
+ api_audience_expect = [host, "https://language2.com"]
+ for t, e in zip(api_audience_tests, api_audience_expect):
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ gdch_mock = mock.MagicMock()
+ type(gdch_mock).with_gdch_audience = mock.PropertyMock(
+ return_value=gdch_mock
)
- )
- )
+ adc.return_value = (gdch_mock, None)
+ transport_class(host=host, api_audience=t)
+ gdch_mock.with_gdch_audience.assert_called_once_with(e)
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_authorization_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(transport=transport)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.NetworkSecurityGrpcTransport, grpc_helpers),
+ (transports.NetworkSecurityGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_network_security_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
with mock.patch.object(
- 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.NetworkSecurityRestInterceptor, "post_create_authorization_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_create_authorization_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcn_authorization_policy.CreateAuthorizationPolicyRequest.pb(
- gcn_authorization_policy.CreateAuthorizationPolicyRequest()
- )
- 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 = gcn_authorization_policy.CreateAuthorizationPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
- client.create_authorization_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
+ create_channel.assert_called_with(
+ "networksecurity.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ scopes=["1", "2"],
+ default_host="networksecurity.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
],
)
- pre.assert_called_once()
- post.assert_called_once()
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.NetworkSecurityGrpcTransport,
+ transports.NetworkSecurityGrpcAsyncIOTransport,
+ ],
+)
+def test_network_security_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
-def test_create_authorization_policy_rest_bad_request(
- transport: str = "rest",
- request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest,
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request_init["authorization_policy"] = {
- "name": "name_value",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "action": 1,
- "rules": [
- {
- "sources": [
- {
- "principals": ["principals_value1", "principals_value2"],
- "ip_blocks": ["ip_blocks_value1", "ip_blocks_value2"],
- }
- ],
- "destinations": [
- {
- "hosts": ["hosts_value1", "hosts_value2"],
- "ports": [569, 570],
- "methods": ["methods_value1", "methods_value2"],
- "http_header_match": {
- "regex_match": "regex_match_value",
- "header_name": "header_name_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_authorization_policy(request)
-
-
-def test_create_authorization_policy_rest_flattened():
- client = NetworkSecurityClient(
- 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/sample2"}
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- authorization_policy=gcn_authorization_policy.AuthorizationPolicy(
- name="name_value"
- ),
- authorization_policy_id="authorization_policy_id_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_authorization_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{parent=projects/*/locations/*}/authorizationPolicies"
- % client.transport._host,
- args[1],
- )
-
-
-def test_create_authorization_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_authorization_policy(
- gcn_authorization_policy.CreateAuthorizationPolicyRequest(),
- parent="parent_value",
- authorization_policy=gcn_authorization_policy.AuthorizationPolicy(
- name="name_value"
- ),
- authorization_policy_id="authorization_policy_id_value",
- )
-
-
-def test_create_authorization_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcn_authorization_policy.UpdateAuthorizationPolicyRequest,
- dict,
- ],
-)
-def test_update_authorization_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "authorization_policy": {
- "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- }
- }
- request_init["authorization_policy"] = {
- "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "action": 1,
- "rules": [
- {
- "sources": [
- {
- "principals": ["principals_value1", "principals_value2"],
- "ip_blocks": ["ip_blocks_value1", "ip_blocks_value2"],
- }
- ],
- "destinations": [
- {
- "hosts": ["hosts_value1", "hosts_value2"],
- "ports": [569, 570],
- "methods": ["methods_value1", "methods_value2"],
- "http_header_match": {
- "regex_match": "regex_match_value",
- "header_name": "header_name_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_authorization_policy(request)
-
- # Establish that the response is the type that we expect.
- assert response.operation.name == "operations/spam"
-
-
-def test_update_authorization_policy_rest_required_fields(
- request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- 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_authorization_policy._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_authorization_policy._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 = NetworkSecurityClient(
- 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_authorization_policy(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_update_authorization_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.update_authorization_policy._get_unset_required_fields({})
- assert set(unset_fields) == (set(("updateMask",)) & set(("authorizationPolicy",)))
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_authorization_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_update_authorization_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_update_authorization_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcn_authorization_policy.UpdateAuthorizationPolicyRequest.pb(
- gcn_authorization_policy.UpdateAuthorizationPolicyRequest()
- )
- 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 = gcn_authorization_policy.UpdateAuthorizationPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.update_authorization_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_authorization_policy_rest_bad_request(
- transport: str = "rest",
- request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest,
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "authorization_policy": {
- "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- }
- }
- request_init["authorization_policy"] = {
- "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "action": 1,
- "rules": [
- {
- "sources": [
- {
- "principals": ["principals_value1", "principals_value2"],
- "ip_blocks": ["ip_blocks_value1", "ip_blocks_value2"],
- }
- ],
- "destinations": [
- {
- "hosts": ["hosts_value1", "hosts_value2"],
- "ports": [569, 570],
- "methods": ["methods_value1", "methods_value2"],
- "http_header_match": {
- "regex_match": "regex_match_value",
- "header_name": "header_name_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_authorization_policy(request)
-
-
-def test_update_authorization_policy_rest_flattened():
- client = NetworkSecurityClient(
- 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 = {
- "authorization_policy": {
- "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- }
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- authorization_policy=gcn_authorization_policy.AuthorizationPolicy(
- name="name_value"
- ),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.update_authorization_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{authorization_policy.name=projects/*/locations/*/authorizationPolicies/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_update_authorization_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_authorization_policy(
- gcn_authorization_policy.UpdateAuthorizationPolicyRequest(),
- authorization_policy=gcn_authorization_policy.AuthorizationPolicy(
- name="name_value"
- ),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_update_authorization_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- authorization_policy.DeleteAuthorizationPolicyRequest,
- dict,
- ],
-)
-def test_delete_authorization_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = 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_authorization_policy(request)
-
- # Establish that the response is the type that we expect.
- assert response.operation.name == "operations/spam"
-
-
-def test_delete_authorization_policy_rest_required_fields(
- request_type=authorization_policy.DeleteAuthorizationPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- 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_authorization_policy._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_authorization_policy._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 = NetworkSecurityClient(
- 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_authorization_policy(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_delete_authorization_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.delete_authorization_policy._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_authorization_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_delete_authorization_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_delete_authorization_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = authorization_policy.DeleteAuthorizationPolicyRequest.pb(
- authorization_policy.DeleteAuthorizationPolicyRequest()
- )
- 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 = authorization_policy.DeleteAuthorizationPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.delete_authorization_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_authorization_policy_rest_bad_request(
- transport: str = "rest",
- request_type=authorization_policy.DeleteAuthorizationPolicyRequest,
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.delete_authorization_policy(request)
-
-
-def test_delete_authorization_policy_rest_flattened():
- client = NetworkSecurityClient(
- 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/sample2/authorizationPolicies/sample3"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.delete_authorization_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{name=projects/*/locations/*/authorizationPolicies/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_delete_authorization_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_authorization_policy(
- authorization_policy.DeleteAuthorizationPolicyRequest(),
- name="name_value",
- )
-
-
-def test_delete_authorization_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- server_tls_policy.ListServerTlsPoliciesRequest,
- dict,
- ],
-)
-def test_list_server_tls_policies_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = server_tls_policy.ListServerTlsPoliciesResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = server_tls_policy.ListServerTlsPoliciesResponse.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_server_tls_policies(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListServerTlsPoliciesPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-def test_list_server_tls_policies_rest_required_fields(
- request_type=server_tls_policy.ListServerTlsPoliciesRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(
- pb_request,
- including_default_value_fields=False,
- use_integers_for_enums=False,
- )
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).list_server_tls_policies._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_server_tls_policies._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(
- (
- "page_size",
- "page_token",
- )
- )
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
-
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = server_tls_policy.ListServerTlsPoliciesResponse()
- # 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 = server_tls_policy.ListServerTlsPoliciesResponse.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_server_tls_policies(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_list_server_tls_policies_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.list_server_tls_policies._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(
- (
- "pageSize",
- "pageToken",
- )
- )
- & set(("parent",))
- )
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_server_tls_policies_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_list_server_tls_policies"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_list_server_tls_policies"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = server_tls_policy.ListServerTlsPoliciesRequest.pb(
- server_tls_policy.ListServerTlsPoliciesRequest()
- )
- 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 = (
- server_tls_policy.ListServerTlsPoliciesResponse.to_json(
- server_tls_policy.ListServerTlsPoliciesResponse()
- )
- )
-
- request = server_tls_policy.ListServerTlsPoliciesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = server_tls_policy.ListServerTlsPoliciesResponse()
-
- client.list_server_tls_policies(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_list_server_tls_policies_rest_bad_request(
- transport: str = "rest", request_type=server_tls_policy.ListServerTlsPoliciesRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_server_tls_policies(request)
-
-
-def test_list_server_tls_policies_rest_flattened():
- client = NetworkSecurityClient(
- 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 = server_tls_policy.ListServerTlsPoliciesResponse()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {"parent": "projects/sample1/locations/sample2"}
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = server_tls_policy.ListServerTlsPoliciesResponse.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_server_tls_policies(**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/v1beta1/{parent=projects/*/locations/*}/serverTlsPolicies"
- % client.transport._host,
- args[1],
- )
-
-
-def test_list_server_tls_policies_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.list_server_tls_policies(
- server_tls_policy.ListServerTlsPoliciesRequest(),
- parent="parent_value",
- )
-
-
-def test_list_server_tls_policies_rest_pager(transport: str = "rest"):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # TODO(kbandes): remove this mock unless there's a good reason for it.
- # with mock.patch.object(path_template, 'transcode') as transcode:
- # Set the response as a series of pages
- response = (
- server_tls_policy.ListServerTlsPoliciesResponse(
- server_tls_policies=[
- server_tls_policy.ServerTlsPolicy(),
- server_tls_policy.ServerTlsPolicy(),
- server_tls_policy.ServerTlsPolicy(),
- ],
- next_page_token="abc",
- ),
- server_tls_policy.ListServerTlsPoliciesResponse(
- server_tls_policies=[],
- next_page_token="def",
- ),
- server_tls_policy.ListServerTlsPoliciesResponse(
- server_tls_policies=[
- server_tls_policy.ServerTlsPolicy(),
- ],
- next_page_token="ghi",
- ),
- server_tls_policy.ListServerTlsPoliciesResponse(
- server_tls_policies=[
- server_tls_policy.ServerTlsPolicy(),
- server_tls_policy.ServerTlsPolicy(),
- ],
- ),
- )
- # Two responses for two calls
- response = response + response
-
- # Wrap the values into proper Response objs
- response = tuple(
- server_tls_policy.ListServerTlsPoliciesResponse.to_json(x) for x in response
- )
- return_values = tuple(Response() for i in response)
- for return_val, response_val in zip(return_values, response):
- return_val._content = response_val.encode("UTF-8")
- return_val.status_code = 200
- req.side_effect = return_values
-
- sample_request = {"parent": "projects/sample1/locations/sample2"}
-
- pager = client.list_server_tls_policies(request=sample_request)
-
- results = list(pager)
- assert len(results) == 6
- assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) for i in results)
-
- pages = list(client.list_server_tls_policies(request=sample_request).pages)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- server_tls_policy.GetServerTlsPolicyRequest,
- dict,
- ],
-)
-def test_get_server_tls_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = server_tls_policy.ServerTlsPolicy(
- name="name_value",
- description="description_value",
- allow_open=True,
- )
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = server_tls_policy.ServerTlsPolicy.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_server_tls_policy(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, server_tls_policy.ServerTlsPolicy)
- assert response.name == "name_value"
- assert response.description == "description_value"
- assert response.allow_open is True
-
-
-def test_get_server_tls_policy_rest_required_fields(
- request_type=server_tls_policy.GetServerTlsPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- 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_server_tls_policy._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_server_tls_policy._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 = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = server_tls_policy.ServerTlsPolicy()
- # 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 = server_tls_policy.ServerTlsPolicy.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_server_tls_policy(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_get_server_tls_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.get_server_tls_policy._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_server_tls_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_get_server_tls_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_get_server_tls_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = server_tls_policy.GetServerTlsPolicyRequest.pb(
- server_tls_policy.GetServerTlsPolicyRequest()
- )
- 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 = server_tls_policy.ServerTlsPolicy.to_json(
- server_tls_policy.ServerTlsPolicy()
- )
-
- request = server_tls_policy.GetServerTlsPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = server_tls_policy.ServerTlsPolicy()
-
- client.get_server_tls_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_server_tls_policy_rest_bad_request(
- transport: str = "rest", request_type=server_tls_policy.GetServerTlsPolicyRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_server_tls_policy(request)
-
-
-def test_get_server_tls_policy_rest_flattened():
- client = NetworkSecurityClient(
- 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 = server_tls_policy.ServerTlsPolicy()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = server_tls_policy.ServerTlsPolicy.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_server_tls_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{name=projects/*/locations/*/serverTlsPolicies/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_get_server_tls_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_server_tls_policy(
- server_tls_policy.GetServerTlsPolicyRequest(),
- name="name_value",
- )
-
-
-def test_get_server_tls_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcn_server_tls_policy.CreateServerTlsPolicyRequest,
- dict,
- ],
-)
-def test_create_server_tls_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request_init["server_tls_policy"] = {
- "name": "name_value",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "allow_open": True,
- "server_certificate": {
- "grpc_endpoint": {"target_uri": "target_uri_value"},
- "certificate_provider_instance": {
- "plugin_instance": "plugin_instance_value"
- },
- },
- "mtls_policy": {
- "client_validation_ca": [
- {"grpc_endpoint": {}, "certificate_provider_instance": {}}
- ]
- },
- }
- 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_server_tls_policy(request)
-
- # Establish that the response is the type that we expect.
- assert response.operation.name == "operations/spam"
-
-
-def test_create_server_tls_policy_rest_required_fields(
- request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request_init["server_tls_policy_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 "serverTlsPolicyId" not in jsonified_request
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_server_tls_policy._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
- assert "serverTlsPolicyId" in jsonified_request
- assert (
- jsonified_request["serverTlsPolicyId"] == request_init["server_tls_policy_id"]
- )
-
- jsonified_request["parent"] = "parent_value"
- jsonified_request["serverTlsPolicyId"] = "server_tls_policy_id_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_server_tls_policy._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("server_tls_policy_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 "serverTlsPolicyId" in jsonified_request
- assert jsonified_request["serverTlsPolicyId"] == "server_tls_policy_id_value"
-
- client = NetworkSecurityClient(
- 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_server_tls_policy(request)
-
- expected_params = [
- (
- "serverTlsPolicyId",
- "",
- ),
- ("$alt", "json;enum-encoding=int"),
- ]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_create_server_tls_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.create_server_tls_policy._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(("serverTlsPolicyId",))
- & set(
- (
- "parent",
- "serverTlsPolicyId",
- "serverTlsPolicy",
- )
- )
- )
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_server_tls_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_create_server_tls_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_create_server_tls_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcn_server_tls_policy.CreateServerTlsPolicyRequest.pb(
- gcn_server_tls_policy.CreateServerTlsPolicyRequest()
- )
- 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 = gcn_server_tls_policy.CreateServerTlsPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.create_server_tls_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_server_tls_policy_rest_bad_request(
- transport: str = "rest",
- request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest,
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request_init["server_tls_policy"] = {
- "name": "name_value",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "allow_open": True,
- "server_certificate": {
- "grpc_endpoint": {"target_uri": "target_uri_value"},
- "certificate_provider_instance": {
- "plugin_instance": "plugin_instance_value"
- },
- },
- "mtls_policy": {
- "client_validation_ca": [
- {"grpc_endpoint": {}, "certificate_provider_instance": {}}
- ]
- },
- }
- 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_server_tls_policy(request)
-
-
-def test_create_server_tls_policy_rest_flattened():
- client = NetworkSecurityClient(
- 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/sample2"}
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name="name_value"),
- server_tls_policy_id="server_tls_policy_id_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_server_tls_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{parent=projects/*/locations/*}/serverTlsPolicies"
- % client.transport._host,
- args[1],
- )
-
-
-def test_create_server_tls_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_server_tls_policy(
- gcn_server_tls_policy.CreateServerTlsPolicyRequest(),
- parent="parent_value",
- server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name="name_value"),
- server_tls_policy_id="server_tls_policy_id_value",
- )
-
-
-def test_create_server_tls_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcn_server_tls_policy.UpdateServerTlsPolicyRequest,
- dict,
- ],
-)
-def test_update_server_tls_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "server_tls_policy": {
- "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3"
- }
- }
- request_init["server_tls_policy"] = {
- "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "allow_open": True,
- "server_certificate": {
- "grpc_endpoint": {"target_uri": "target_uri_value"},
- "certificate_provider_instance": {
- "plugin_instance": "plugin_instance_value"
- },
- },
- "mtls_policy": {
- "client_validation_ca": [
- {"grpc_endpoint": {}, "certificate_provider_instance": {}}
- ]
- },
- }
- 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_server_tls_policy(request)
-
- # Establish that the response is the type that we expect.
- assert response.operation.name == "operations/spam"
-
-
-def test_update_server_tls_policy_rest_required_fields(
- request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- 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_server_tls_policy._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_server_tls_policy._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 = NetworkSecurityClient(
- 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_server_tls_policy(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_update_server_tls_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.update_server_tls_policy._get_unset_required_fields({})
- assert set(unset_fields) == (set(("updateMask",)) & set(("serverTlsPolicy",)))
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_server_tls_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_update_server_tls_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_update_server_tls_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcn_server_tls_policy.UpdateServerTlsPolicyRequest.pb(
- gcn_server_tls_policy.UpdateServerTlsPolicyRequest()
- )
- 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 = gcn_server_tls_policy.UpdateServerTlsPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.update_server_tls_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_server_tls_policy_rest_bad_request(
- transport: str = "rest",
- request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest,
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "server_tls_policy": {
- "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3"
- }
- }
- request_init["server_tls_policy"] = {
- "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "allow_open": True,
- "server_certificate": {
- "grpc_endpoint": {"target_uri": "target_uri_value"},
- "certificate_provider_instance": {
- "plugin_instance": "plugin_instance_value"
- },
- },
- "mtls_policy": {
- "client_validation_ca": [
- {"grpc_endpoint": {}, "certificate_provider_instance": {}}
- ]
- },
- }
- 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_server_tls_policy(request)
-
-
-def test_update_server_tls_policy_rest_flattened():
- client = NetworkSecurityClient(
- 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 = {
- "server_tls_policy": {
- "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3"
- }
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.update_server_tls_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{server_tls_policy.name=projects/*/locations/*/serverTlsPolicies/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_update_server_tls_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_server_tls_policy(
- gcn_server_tls_policy.UpdateServerTlsPolicyRequest(),
- server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_update_server_tls_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- server_tls_policy.DeleteServerTlsPolicyRequest,
- dict,
- ],
-)
-def test_delete_server_tls_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = 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_server_tls_policy(request)
-
- # Establish that the response is the type that we expect.
- assert response.operation.name == "operations/spam"
-
-
-def test_delete_server_tls_policy_rest_required_fields(
- request_type=server_tls_policy.DeleteServerTlsPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- 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_server_tls_policy._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_server_tls_policy._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 = NetworkSecurityClient(
- 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_server_tls_policy(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_delete_server_tls_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.delete_server_tls_policy._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_server_tls_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_delete_server_tls_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_delete_server_tls_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = server_tls_policy.DeleteServerTlsPolicyRequest.pb(
- server_tls_policy.DeleteServerTlsPolicyRequest()
- )
- 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 = server_tls_policy.DeleteServerTlsPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.delete_server_tls_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_server_tls_policy_rest_bad_request(
- transport: str = "rest", request_type=server_tls_policy.DeleteServerTlsPolicyRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/serverTlsPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.delete_server_tls_policy(request)
-
-
-def test_delete_server_tls_policy_rest_flattened():
- client = NetworkSecurityClient(
- 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/sample2/serverTlsPolicies/sample3"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.delete_server_tls_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{name=projects/*/locations/*/serverTlsPolicies/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_delete_server_tls_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_server_tls_policy(
- server_tls_policy.DeleteServerTlsPolicyRequest(),
- name="name_value",
- )
-
-
-def test_delete_server_tls_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- client_tls_policy.ListClientTlsPoliciesRequest,
- dict,
- ],
-)
-def test_list_client_tls_policies_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = client_tls_policy.ListClientTlsPoliciesResponse(
- next_page_token="next_page_token_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = client_tls_policy.ListClientTlsPoliciesResponse.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_client_tls_policies(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListClientTlsPoliciesPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-def test_list_client_tls_policies_rest_required_fields(
- request_type=client_tls_policy.ListClientTlsPoliciesRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request = request_type(**request_init)
- pb_request = request_type.pb(request)
- jsonified_request = json.loads(
- json_format.MessageToJson(
- pb_request,
- including_default_value_fields=False,
- use_integers_for_enums=False,
- )
- )
-
- # verify fields with default values are dropped
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).list_client_tls_policies._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_client_tls_policies._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(
- (
- "page_size",
- "page_token",
- )
- )
- jsonified_request.update(unset_fields)
-
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
-
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = client_tls_policy.ListClientTlsPoliciesResponse()
- # 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 = client_tls_policy.ListClientTlsPoliciesResponse.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_client_tls_policies(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_list_client_tls_policies_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.list_client_tls_policies._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(
- (
- "pageSize",
- "pageToken",
- )
- )
- & set(("parent",))
- )
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_client_tls_policies_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_list_client_tls_policies"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_list_client_tls_policies"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = client_tls_policy.ListClientTlsPoliciesRequest.pb(
- client_tls_policy.ListClientTlsPoliciesRequest()
- )
- 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 = (
- client_tls_policy.ListClientTlsPoliciesResponse.to_json(
- client_tls_policy.ListClientTlsPoliciesResponse()
- )
- )
-
- request = client_tls_policy.ListClientTlsPoliciesRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = client_tls_policy.ListClientTlsPoliciesResponse()
-
- client.list_client_tls_policies(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_list_client_tls_policies_rest_bad_request(
- transport: str = "rest", request_type=client_tls_policy.ListClientTlsPoliciesRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.list_client_tls_policies(request)
-
-
-def test_list_client_tls_policies_rest_flattened():
- client = NetworkSecurityClient(
- 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 = client_tls_policy.ListClientTlsPoliciesResponse()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {"parent": "projects/sample1/locations/sample2"}
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = client_tls_policy.ListClientTlsPoliciesResponse.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_client_tls_policies(**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/v1beta1/{parent=projects/*/locations/*}/clientTlsPolicies"
- % client.transport._host,
- args[1],
- )
-
-
-def test_list_client_tls_policies_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.list_client_tls_policies(
- client_tls_policy.ListClientTlsPoliciesRequest(),
- parent="parent_value",
- )
-
-
-def test_list_client_tls_policies_rest_pager(transport: str = "rest"):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # TODO(kbandes): remove this mock unless there's a good reason for it.
- # with mock.patch.object(path_template, 'transcode') as transcode:
- # Set the response as a series of pages
- response = (
- client_tls_policy.ListClientTlsPoliciesResponse(
- client_tls_policies=[
- client_tls_policy.ClientTlsPolicy(),
- client_tls_policy.ClientTlsPolicy(),
- client_tls_policy.ClientTlsPolicy(),
- ],
- next_page_token="abc",
- ),
- client_tls_policy.ListClientTlsPoliciesResponse(
- client_tls_policies=[],
- next_page_token="def",
- ),
- client_tls_policy.ListClientTlsPoliciesResponse(
- client_tls_policies=[
- client_tls_policy.ClientTlsPolicy(),
- ],
- next_page_token="ghi",
- ),
- client_tls_policy.ListClientTlsPoliciesResponse(
- client_tls_policies=[
- client_tls_policy.ClientTlsPolicy(),
- client_tls_policy.ClientTlsPolicy(),
- ],
- ),
- )
- # Two responses for two calls
- response = response + response
-
- # Wrap the values into proper Response objs
- response = tuple(
- client_tls_policy.ListClientTlsPoliciesResponse.to_json(x) for x in response
- )
- return_values = tuple(Response() for i in response)
- for return_val, response_val in zip(return_values, response):
- return_val._content = response_val.encode("UTF-8")
- return_val.status_code = 200
- req.side_effect = return_values
-
- sample_request = {"parent": "projects/sample1/locations/sample2"}
-
- pager = client.list_client_tls_policies(request=sample_request)
-
- results = list(pager)
- assert len(results) == 6
- assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) for i in results)
-
- pages = list(client.list_client_tls_policies(request=sample_request).pages)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- client_tls_policy.GetClientTlsPolicyRequest,
- dict,
- ],
-)
-def test_get_client_tls_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = client_tls_policy.ClientTlsPolicy(
- name="name_value",
- description="description_value",
- sni="sni_value",
- )
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = client_tls_policy.ClientTlsPolicy.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_client_tls_policy(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, client_tls_policy.ClientTlsPolicy)
- assert response.name == "name_value"
- assert response.description == "description_value"
- assert response.sni == "sni_value"
-
-
-def test_get_client_tls_policy_rest_required_fields(
- request_type=client_tls_policy.GetClientTlsPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- 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_client_tls_policy._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_client_tls_policy._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 = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
-
- # Designate an appropriate value for the returned response.
- return_value = client_tls_policy.ClientTlsPolicy()
- # 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 = client_tls_policy.ClientTlsPolicy.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_client_tls_policy(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_get_client_tls_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.get_client_tls_policy._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_client_tls_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_get_client_tls_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_get_client_tls_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = client_tls_policy.GetClientTlsPolicyRequest.pb(
- client_tls_policy.GetClientTlsPolicyRequest()
- )
- 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 = client_tls_policy.ClientTlsPolicy.to_json(
- client_tls_policy.ClientTlsPolicy()
- )
-
- request = client_tls_policy.GetClientTlsPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = client_tls_policy.ClientTlsPolicy()
-
- client.get_client_tls_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_get_client_tls_policy_rest_bad_request(
- transport: str = "rest", request_type=client_tls_policy.GetClientTlsPolicyRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_client_tls_policy(request)
-
-
-def test_get_client_tls_policy_rest_flattened():
- client = NetworkSecurityClient(
- 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 = client_tls_policy.ClientTlsPolicy()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- pb_return_value = client_tls_policy.ClientTlsPolicy.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_client_tls_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{name=projects/*/locations/*/clientTlsPolicies/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_get_client_tls_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_client_tls_policy(
- client_tls_policy.GetClientTlsPolicyRequest(),
- name="name_value",
- )
-
-
-def test_get_client_tls_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcn_client_tls_policy.CreateClientTlsPolicyRequest,
- dict,
- ],
-)
-def test_create_client_tls_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request_init["client_tls_policy"] = {
- "name": "name_value",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "sni": "sni_value",
- "client_certificate": {
- "grpc_endpoint": {"target_uri": "target_uri_value"},
- "certificate_provider_instance": {
- "plugin_instance": "plugin_instance_value"
- },
- },
- "server_validation_ca": [
- {"grpc_endpoint": {}, "certificate_provider_instance": {}}
- ],
- }
- 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_client_tls_policy(request)
-
- # Establish that the response is the type that we expect.
- assert response.operation.name == "operations/spam"
-
-
-def test_create_client_tls_policy_rest_required_fields(
- request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- request_init = {}
- request_init["parent"] = ""
- request_init["client_tls_policy_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 "clientTlsPolicyId" not in jsonified_request
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_client_tls_policy._get_unset_required_fields(jsonified_request)
- jsonified_request.update(unset_fields)
-
- # verify required fields with default values are now present
- assert "clientTlsPolicyId" in jsonified_request
- assert (
- jsonified_request["clientTlsPolicyId"] == request_init["client_tls_policy_id"]
- )
-
- jsonified_request["parent"] = "parent_value"
- jsonified_request["clientTlsPolicyId"] = "client_tls_policy_id_value"
-
- unset_fields = transport_class(
- credentials=ga_credentials.AnonymousCredentials()
- ).create_client_tls_policy._get_unset_required_fields(jsonified_request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("client_tls_policy_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 "clientTlsPolicyId" in jsonified_request
- assert jsonified_request["clientTlsPolicyId"] == "client_tls_policy_id_value"
-
- client = NetworkSecurityClient(
- 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_client_tls_policy(request)
-
- expected_params = [
- (
- "clientTlsPolicyId",
- "",
- ),
- ("$alt", "json;enum-encoding=int"),
- ]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_create_client_tls_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.create_client_tls_policy._get_unset_required_fields({})
- assert set(unset_fields) == (
- set(("clientTlsPolicyId",))
- & set(
- (
- "parent",
- "clientTlsPolicyId",
- "clientTlsPolicy",
- )
- )
- )
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_client_tls_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_create_client_tls_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_create_client_tls_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb(
- gcn_client_tls_policy.CreateClientTlsPolicyRequest()
- )
- 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 = gcn_client_tls_policy.CreateClientTlsPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.create_client_tls_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_create_client_tls_policy_rest_bad_request(
- transport: str = "rest",
- request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest,
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
- request_init["client_tls_policy"] = {
- "name": "name_value",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "sni": "sni_value",
- "client_certificate": {
- "grpc_endpoint": {"target_uri": "target_uri_value"},
- "certificate_provider_instance": {
- "plugin_instance": "plugin_instance_value"
- },
- },
- "server_validation_ca": [
- {"grpc_endpoint": {}, "certificate_provider_instance": {}}
- ],
- }
- 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_client_tls_policy(request)
-
-
-def test_create_client_tls_policy_rest_flattened():
- client = NetworkSecurityClient(
- 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/sample2"}
-
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name="name_value"),
- client_tls_policy_id="client_tls_policy_id_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_client_tls_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{parent=projects/*/locations/*}/clientTlsPolicies"
- % client.transport._host,
- args[1],
- )
-
-
-def test_create_client_tls_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_client_tls_policy(
- gcn_client_tls_policy.CreateClientTlsPolicyRequest(),
- parent="parent_value",
- client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name="name_value"),
- client_tls_policy_id="client_tls_policy_id_value",
- )
-
-
-def test_create_client_tls_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- gcn_client_tls_policy.UpdateClientTlsPolicyRequest,
- dict,
- ],
-)
-def test_update_client_tls_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "client_tls_policy": {
- "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3"
- }
- }
- request_init["client_tls_policy"] = {
- "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "sni": "sni_value",
- "client_certificate": {
- "grpc_endpoint": {"target_uri": "target_uri_value"},
- "certificate_provider_instance": {
- "plugin_instance": "plugin_instance_value"
- },
- },
- "server_validation_ca": [
- {"grpc_endpoint": {}, "certificate_provider_instance": {}}
- ],
- }
- 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_client_tls_policy(request)
-
- # Establish that the response is the type that we expect.
- assert response.operation.name == "operations/spam"
-
-
-def test_update_client_tls_policy_rest_required_fields(
- request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- 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_client_tls_policy._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_client_tls_policy._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 = NetworkSecurityClient(
- 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_client_tls_policy(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_update_client_tls_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.update_client_tls_policy._get_unset_required_fields({})
- assert set(unset_fields) == (set(("updateMask",)) & set(("clientTlsPolicy",)))
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_client_tls_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_update_client_tls_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_update_client_tls_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb(
- gcn_client_tls_policy.UpdateClientTlsPolicyRequest()
- )
- 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 = gcn_client_tls_policy.UpdateClientTlsPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.update_client_tls_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_update_client_tls_policy_rest_bad_request(
- transport: str = "rest",
- request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest,
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "client_tls_policy": {
- "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3"
- }
- }
- request_init["client_tls_policy"] = {
- "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3",
- "description": "description_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "labels": {},
- "sni": "sni_value",
- "client_certificate": {
- "grpc_endpoint": {"target_uri": "target_uri_value"},
- "certificate_provider_instance": {
- "plugin_instance": "plugin_instance_value"
- },
- },
- "server_validation_ca": [
- {"grpc_endpoint": {}, "certificate_provider_instance": {}}
- ],
- }
- 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_client_tls_policy(request)
-
-
-def test_update_client_tls_policy_rest_flattened():
- client = NetworkSecurityClient(
- 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 = {
- "client_tls_policy": {
- "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3"
- }
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.update_client_tls_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_update_client_tls_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_client_tls_policy(
- gcn_client_tls_policy.UpdateClientTlsPolicyRequest(),
- client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_update_client_tls_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- client_tls_policy.DeleteClientTlsPolicyRequest,
- dict,
- ],
-)
-def test_delete_client_tls_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = 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_client_tls_policy(request)
-
- # Establish that the response is the type that we expect.
- assert response.operation.name == "operations/spam"
-
-
-def test_delete_client_tls_policy_rest_required_fields(
- request_type=client_tls_policy.DeleteClientTlsPolicyRequest,
-):
- transport_class = transports.NetworkSecurityRestTransport
-
- 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_client_tls_policy._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_client_tls_policy._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 = NetworkSecurityClient(
- 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_client_tls_policy(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert expected_params == actual_params
-
-
-def test_delete_client_tls_policy_rest_unset_required_fields():
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials
- )
-
- unset_fields = transport.delete_client_tls_policy._get_unset_required_fields({})
- assert set(unset_fields) == (set(()) & set(("name",)))
-
-
-@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_client_tls_policy_rest_interceptors(null_interceptor):
- transport = transports.NetworkSecurityRestTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- interceptor=None
- if null_interceptor
- else transports.NetworkSecurityRestInterceptor(),
- )
- client = NetworkSecurityClient(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.NetworkSecurityRestInterceptor, "post_delete_client_tls_policy"
- ) as post, mock.patch.object(
- transports.NetworkSecurityRestInterceptor, "pre_delete_client_tls_policy"
- ) as pre:
- pre.assert_not_called()
- post.assert_not_called()
- pb_message = client_tls_policy.DeleteClientTlsPolicyRequest.pb(
- client_tls_policy.DeleteClientTlsPolicyRequest()
- )
- 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 = client_tls_policy.DeleteClientTlsPolicyRequest()
- metadata = [
- ("key", "val"),
- ("cephalopod", "squid"),
- ]
- pre.return_value = request, metadata
- post.return_value = operations_pb2.Operation()
-
- client.delete_client_tls_policy(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
-
-
-def test_delete_client_tls_policy_rest_bad_request(
- transport: str = "rest", request_type=client_tls_policy.DeleteClientTlsPolicyRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "name": "projects/sample1/locations/sample2/clientTlsPolicies/sample3"
- }
- request = request_type(**request_init)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.delete_client_tls_policy(request)
-
-
-def test_delete_client_tls_policy_rest_flattened():
- client = NetworkSecurityClient(
- 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/sample2/clientTlsPolicies/sample3"
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- name="name_value",
- )
- mock_args.update(sample_request)
-
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
-
- client.delete_client_tls_policy(**mock_args)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(req.mock_calls) == 1
- _, args, _ = req.mock_calls[0]
- assert path_template.validate(
- "%s/v1beta1/{name=projects/*/locations/*/clientTlsPolicies/*}"
- % client.transport._host,
- args[1],
- )
-
-
-def test_delete_client_tls_policy_rest_flattened_error(transport: str = "rest"):
- client = NetworkSecurityClient(
- 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_client_tls_policy(
- client_tls_policy.DeleteClientTlsPolicyRequest(),
- name="name_value",
- )
-
-
-def test_delete_client_tls_policy_rest_error():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.NetworkSecurityGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.NetworkSecurityGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = NetworkSecurityClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.NetworkSecurityGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = NetworkSecurityClient(
- 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 = NetworkSecurityClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
-
- # It is an error to provide scopes and a transport instance.
- transport = transports.NetworkSecurityGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = NetworkSecurityClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.NetworkSecurityGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = NetworkSecurityClient(transport=transport)
- assert client.transport is transport
-
-
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.NetworkSecurityGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
- transport = transports.NetworkSecurityGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.NetworkSecurityGrpcTransport,
- transports.NetworkSecurityGrpcAsyncIOTransport,
- transports.NetworkSecurityRestTransport,
- ],
-)
-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 = NetworkSecurityClient.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 = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- assert isinstance(
- client.transport,
- transports.NetworkSecurityGrpcTransport,
- )
-
-
-def test_network_security_base_transport_error():
- # Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(core_exceptions.DuplicateCredentialArgs):
- transport = transports.NetworkSecurityTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- credentials_file="credentials.json",
- )
-
-
-def test_network_security_base_transport():
- # Instantiate the base transport.
- with mock.patch(
- "google.cloud.network_security_v1beta1.services.network_security.transports.NetworkSecurityTransport.__init__"
- ) as Transport:
- Transport.return_value = None
- transport = transports.NetworkSecurityTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
-
- # Every method on the transport should just blindly
- # raise NotImplementedError.
- methods = (
- "list_authorization_policies",
- "get_authorization_policy",
- "create_authorization_policy",
- "update_authorization_policy",
- "delete_authorization_policy",
- "list_server_tls_policies",
- "get_server_tls_policy",
- "create_server_tls_policy",
- "update_server_tls_policy",
- "delete_server_tls_policy",
- "list_client_tls_policies",
- "get_client_tls_policy",
- "create_client_tls_policy",
- "update_client_tls_policy",
- "delete_client_tls_policy",
- "set_iam_policy",
- "get_iam_policy",
- "test_iam_permissions",
- "get_location",
- "list_locations",
- "get_operation",
- "cancel_operation",
- "delete_operation",
- "list_operations",
- )
- 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_network_security_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_security_v1beta1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages"
- ) as Transport:
- Transport.return_value = None
- load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport = transports.NetworkSecurityTransport(
- credentials_file="credentials.json",
- quota_project_id="octopus",
- )
- load_creds.assert_called_once_with(
- "credentials.json",
- scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
- quota_project_id="octopus",
- )
-
-
-def test_network_security_base_transport_with_adc():
- # Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
- "google.cloud.network_security_v1beta1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages"
- ) as Transport:
- Transport.return_value = None
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport = transports.NetworkSecurityTransport()
- adc.assert_called_once()
-
-
-def test_network_security_auth_adc():
- # If no credentials are provided, we should use ADC credentials.
- with mock.patch.object(google.auth, "default", autospec=True) as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- NetworkSecurityClient()
- adc.assert_called_once_with(
- scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
- quota_project_id=None,
- )
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.NetworkSecurityGrpcTransport,
- transports.NetworkSecurityGrpcAsyncIOTransport,
- ],
-)
-def test_network_security_transport_auth_adc(transport_class):
- # If credentials and host are not provided, the transport class should use
- # ADC credentials.
- with mock.patch.object(google.auth, "default", autospec=True) as adc:
- adc.return_value = (ga_credentials.AnonymousCredentials(), None)
- transport_class(quota_project_id="octopus", scopes=["1", "2"])
- adc.assert_called_once_with(
- scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
- quota_project_id="octopus",
- )
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.NetworkSecurityGrpcTransport,
- transports.NetworkSecurityGrpcAsyncIOTransport,
- transports.NetworkSecurityRestTransport,
- ],
-)
-def test_network_security_transport_auth_gdch_credentials(transport_class):
- host = "https://language.com"
- api_audience_tests = [None, "https://language2.com"]
- api_audience_expect = [host, "https://language2.com"]
- for t, e in zip(api_audience_tests, api_audience_expect):
- with mock.patch.object(google.auth, "default", autospec=True) as adc:
- gdch_mock = mock.MagicMock()
- type(gdch_mock).with_gdch_audience = mock.PropertyMock(
- return_value=gdch_mock
- )
- adc.return_value = (gdch_mock, None)
- transport_class(host=host, api_audience=t)
- gdch_mock.with_gdch_audience.assert_called_once_with(e)
-
-
-@pytest.mark.parametrize(
- "transport_class,grpc_helpers",
- [
- (transports.NetworkSecurityGrpcTransport, grpc_helpers),
- (transports.NetworkSecurityGrpcAsyncIOTransport, grpc_helpers_async),
- ],
-)
-def test_network_security_transport_create_channel(transport_class, grpc_helpers):
- # If credentials and host are not provided, the transport class should use
- # ADC credentials.
- with mock.patch.object(
- google.auth, "default", autospec=True
- ) as adc, mock.patch.object(
- grpc_helpers, "create_channel", autospec=True
- ) as create_channel:
- creds = ga_credentials.AnonymousCredentials()
- adc.return_value = (creds, None)
- transport_class(quota_project_id="octopus", scopes=["1", "2"])
-
- create_channel.assert_called_with(
- "networksecurity.googleapis.com:443",
- credentials=creds,
- credentials_file=None,
- quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
- scopes=["1", "2"],
- default_host="networksecurity.googleapis.com",
- ssl_credentials=None,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
-
-
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.NetworkSecurityGrpcTransport,
- transports.NetworkSecurityGrpcAsyncIOTransport,
- ],
-)
-def test_network_security_grpc_transport_client_cert_source_for_mtls(transport_class):
- cred = ga_credentials.AnonymousCredentials()
-
- # Check ssl_channel_credentials is used if provided.
- with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
- mock_ssl_channel_creds = mock.Mock()
- transport_class(
- host="squid.clam.whelk",
- credentials=cred,
- ssl_channel_credentials=mock_ssl_channel_creds,
- )
- mock_create_channel.assert_called_once_with(
- "squid.clam.whelk:443",
- credentials=cred,
- credentials_file=None,
- scopes=None,
- ssl_credentials=mock_ssl_channel_creds,
- quota_project_id=None,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
-
- # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
- # is used.
- with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
- with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
- transport_class(
- credentials=cred,
- client_cert_source_for_mtls=client_cert_source_callback,
- )
- expected_cert, expected_key = client_cert_source_callback()
- mock_ssl_cred.assert_called_once_with(
- certificate_chain=expected_cert, private_key=expected_key
- )
-
-
-def test_network_security_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.NetworkSecurityRestTransport(
- 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_network_security_rest_lro_client():
- client = NetworkSecurityClient(
- 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_network_security_host_no_port(transport_name):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="networksecurity.googleapis.com"
- ),
- transport=transport_name,
- )
- assert client.transport._host == (
- "networksecurity.googleapis.com:443"
- if transport_name in ["grpc", "grpc_asyncio"]
- else "https://networksecurity.googleapis.com"
- )
-
-
-@pytest.mark.parametrize(
- "transport_name",
- [
- "grpc",
- "grpc_asyncio",
- "rest",
- ],
-)
-def test_network_security_host_with_port(transport_name):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="networksecurity.googleapis.com:8000"
- ),
- transport=transport_name,
- )
- assert client.transport._host == (
- "networksecurity.googleapis.com:8000"
- if transport_name in ["grpc", "grpc_asyncio"]
- else "https://networksecurity.googleapis.com:8000"
- )
-
-
-@pytest.mark.parametrize(
- "transport_name",
- [
- "rest",
- ],
-)
-def test_network_security_client_transport_session_collision(transport_name):
- creds1 = ga_credentials.AnonymousCredentials()
- creds2 = ga_credentials.AnonymousCredentials()
- client1 = NetworkSecurityClient(
- credentials=creds1,
- transport=transport_name,
- )
- client2 = NetworkSecurityClient(
- credentials=creds2,
- transport=transport_name,
- )
- session1 = client1.transport.list_authorization_policies._session
- session2 = client2.transport.list_authorization_policies._session
- assert session1 != session2
- session1 = client1.transport.get_authorization_policy._session
- session2 = client2.transport.get_authorization_policy._session
- assert session1 != session2
- session1 = client1.transport.create_authorization_policy._session
- session2 = client2.transport.create_authorization_policy._session
- assert session1 != session2
- session1 = client1.transport.update_authorization_policy._session
- session2 = client2.transport.update_authorization_policy._session
- assert session1 != session2
- session1 = client1.transport.delete_authorization_policy._session
- session2 = client2.transport.delete_authorization_policy._session
- assert session1 != session2
- session1 = client1.transport.list_server_tls_policies._session
- session2 = client2.transport.list_server_tls_policies._session
- assert session1 != session2
- session1 = client1.transport.get_server_tls_policy._session
- session2 = client2.transport.get_server_tls_policy._session
- assert session1 != session2
- session1 = client1.transport.create_server_tls_policy._session
- session2 = client2.transport.create_server_tls_policy._session
- assert session1 != session2
- session1 = client1.transport.update_server_tls_policy._session
- session2 = client2.transport.update_server_tls_policy._session
- assert session1 != session2
- session1 = client1.transport.delete_server_tls_policy._session
- session2 = client2.transport.delete_server_tls_policy._session
- assert session1 != session2
- session1 = client1.transport.list_client_tls_policies._session
- session2 = client2.transport.list_client_tls_policies._session
- assert session1 != session2
- session1 = client1.transport.get_client_tls_policy._session
- session2 = client2.transport.get_client_tls_policy._session
- assert session1 != session2
- session1 = client1.transport.create_client_tls_policy._session
- session2 = client2.transport.create_client_tls_policy._session
- assert session1 != session2
- session1 = client1.transport.update_client_tls_policy._session
- session2 = client2.transport.update_client_tls_policy._session
- assert session1 != session2
- session1 = client1.transport.delete_client_tls_policy._session
- session2 = client2.transport.delete_client_tls_policy._session
- assert session1 != session2
-
-
-def test_network_security_grpc_transport_channel():
- channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
-
- # Check that channel is used if provided.
- transport = transports.NetworkSecurityGrpcTransport(
- host="squid.clam.whelk",
- channel=channel,
- )
- assert transport.grpc_channel == channel
- assert transport._host == "squid.clam.whelk:443"
- assert transport._ssl_channel_credentials == None
-
-
-def test_network_security_grpc_asyncio_transport_channel():
- channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
-
- # Check that channel is used if provided.
- transport = transports.NetworkSecurityGrpcAsyncIOTransport(
- host="squid.clam.whelk",
- channel=channel,
- )
- assert transport.grpc_channel == channel
- assert transport._host == "squid.clam.whelk:443"
- assert transport._ssl_channel_credentials == None
-
-
-# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
-# removed from grpc/grpc_asyncio transport constructor.
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.NetworkSecurityGrpcTransport,
- transports.NetworkSecurityGrpcAsyncIOTransport,
- ],
-)
-def test_network_security_transport_channel_mtls_with_client_cert_source(
- transport_class,
-):
- with mock.patch(
- "grpc.ssl_channel_credentials", autospec=True
- ) as grpc_ssl_channel_cred:
- with mock.patch.object(
- transport_class, "create_channel"
- ) as grpc_create_channel:
- mock_ssl_cred = mock.Mock()
- grpc_ssl_channel_cred.return_value = mock_ssl_cred
-
- mock_grpc_channel = mock.Mock()
- grpc_create_channel.return_value = mock_grpc_channel
-
- cred = ga_credentials.AnonymousCredentials()
- with pytest.warns(DeprecationWarning):
- with mock.patch.object(google.auth, "default") as adc:
- adc.return_value = (cred, None)
- transport = transport_class(
- host="squid.clam.whelk",
- api_mtls_endpoint="mtls.squid.clam.whelk",
- client_cert_source=client_cert_source_callback,
- )
- adc.assert_called_once()
-
- grpc_ssl_channel_cred.assert_called_once_with(
- certificate_chain=b"cert bytes", private_key=b"key bytes"
- )
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=cred,
- credentials_file=None,
- scopes=None,
- ssl_credentials=mock_ssl_cred,
- quota_project_id=None,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- assert transport.grpc_channel == mock_grpc_channel
- assert transport._ssl_channel_credentials == mock_ssl_cred
-
-
-# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
-# removed from grpc/grpc_asyncio transport constructor.
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.NetworkSecurityGrpcTransport,
- transports.NetworkSecurityGrpcAsyncIOTransport,
- ],
-)
-def test_network_security_transport_channel_mtls_with_adc(transport_class):
- mock_ssl_cred = mock.Mock()
- with mock.patch.multiple(
- "google.auth.transport.grpc.SslCredentials",
- __init__=mock.Mock(return_value=None),
- ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
- ):
- with mock.patch.object(
- transport_class, "create_channel"
- ) as grpc_create_channel:
- mock_grpc_channel = mock.Mock()
- grpc_create_channel.return_value = mock_grpc_channel
- mock_cred = mock.Mock()
-
- with pytest.warns(DeprecationWarning):
- transport = transport_class(
- host="squid.clam.whelk",
- credentials=mock_cred,
- api_mtls_endpoint="mtls.squid.clam.whelk",
- client_cert_source=None,
- )
-
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=mock_cred,
- credentials_file=None,
- scopes=None,
- ssl_credentials=mock_ssl_cred,
- quota_project_id=None,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- assert transport.grpc_channel == mock_grpc_channel
-
-
-def test_network_security_grpc_lro_client():
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
- transport = client.transport
-
- # Ensure that we have a api-core operations client.
- assert isinstance(
- transport.operations_client,
- operations_v1.OperationsClient,
- )
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
-
-
-def test_network_security_grpc_lro_async_client():
- client = NetworkSecurityAsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc_asyncio",
- )
- transport = client.transport
-
- # Ensure that we have a api-core operations client.
- assert isinstance(
- transport.operations_client,
- operations_v1.OperationsAsyncClient,
- )
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
-
-
-def test_authorization_policy_path():
- project = "squid"
- location = "clam"
- authorization_policy = "whelk"
- expected = "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format(
- project=project,
- location=location,
- authorization_policy=authorization_policy,
- )
- actual = NetworkSecurityClient.authorization_policy_path(
- project, location, authorization_policy
- )
- assert expected == actual
-
-
-def test_parse_authorization_policy_path():
- expected = {
- "project": "octopus",
- "location": "oyster",
- "authorization_policy": "nudibranch",
- }
- path = NetworkSecurityClient.authorization_policy_path(**expected)
-
- # Check that the path construction is reversible.
- actual = NetworkSecurityClient.parse_authorization_policy_path(path)
- assert expected == actual
-
-
-def test_client_tls_policy_path():
- project = "cuttlefish"
- location = "mussel"
- client_tls_policy = "winkle"
- expected = "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(
- project=project,
- location=location,
- client_tls_policy=client_tls_policy,
- )
- actual = NetworkSecurityClient.client_tls_policy_path(
- project, location, client_tls_policy
- )
- assert expected == actual
-
-
-def test_parse_client_tls_policy_path():
- expected = {
- "project": "nautilus",
- "location": "scallop",
- "client_tls_policy": "abalone",
- }
- path = NetworkSecurityClient.client_tls_policy_path(**expected)
-
- # Check that the path construction is reversible.
- actual = NetworkSecurityClient.parse_client_tls_policy_path(path)
- assert expected == actual
-
-
-def test_server_tls_policy_path():
- project = "squid"
- location = "clam"
- server_tls_policy = "whelk"
- expected = "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format(
- project=project,
- location=location,
- server_tls_policy=server_tls_policy,
- )
- actual = NetworkSecurityClient.server_tls_policy_path(
- project, location, server_tls_policy
- )
- assert expected == actual
-
-
-def test_parse_server_tls_policy_path():
- expected = {
- "project": "octopus",
- "location": "oyster",
- "server_tls_policy": "nudibranch",
- }
- path = NetworkSecurityClient.server_tls_policy_path(**expected)
-
- # Check that the path construction is reversible.
- actual = NetworkSecurityClient.parse_server_tls_policy_path(path)
- assert expected == actual
-
-
-def test_common_billing_account_path():
- billing_account = "cuttlefish"
- expected = "billingAccounts/{billing_account}".format(
- billing_account=billing_account,
- )
- actual = NetworkSecurityClient.common_billing_account_path(billing_account)
- assert expected == actual
-
-
-def test_parse_common_billing_account_path():
- expected = {
- "billing_account": "mussel",
- }
- path = NetworkSecurityClient.common_billing_account_path(**expected)
-
- # Check that the path construction is reversible.
- actual = NetworkSecurityClient.parse_common_billing_account_path(path)
- assert expected == actual
-
-
-def test_common_folder_path():
- folder = "winkle"
- expected = "folders/{folder}".format(
- folder=folder,
- )
- actual = NetworkSecurityClient.common_folder_path(folder)
- assert expected == actual
-
-
-def test_parse_common_folder_path():
- expected = {
- "folder": "nautilus",
- }
- path = NetworkSecurityClient.common_folder_path(**expected)
-
- # Check that the path construction is reversible.
- actual = NetworkSecurityClient.parse_common_folder_path(path)
- assert expected == actual
-
-
-def test_common_organization_path():
- organization = "scallop"
- expected = "organizations/{organization}".format(
- organization=organization,
- )
- actual = NetworkSecurityClient.common_organization_path(organization)
- assert expected == actual
-
-
-def test_parse_common_organization_path():
- expected = {
- "organization": "abalone",
- }
- path = NetworkSecurityClient.common_organization_path(**expected)
-
- # Check that the path construction is reversible.
- actual = NetworkSecurityClient.parse_common_organization_path(path)
- assert expected == actual
-
-
-def test_common_project_path():
- project = "squid"
- expected = "projects/{project}".format(
- project=project,
- )
- actual = NetworkSecurityClient.common_project_path(project)
- assert expected == actual
-
-
-def test_parse_common_project_path():
- expected = {
- "project": "clam",
- }
- path = NetworkSecurityClient.common_project_path(**expected)
-
- # Check that the path construction is reversible.
- actual = NetworkSecurityClient.parse_common_project_path(path)
- assert expected == actual
-
-
-def test_common_location_path():
- project = "whelk"
- location = "octopus"
- expected = "projects/{project}/locations/{location}".format(
- project=project,
- location=location,
- )
- actual = NetworkSecurityClient.common_location_path(project, location)
- assert expected == actual
-
-
-def test_parse_common_location_path():
- expected = {
- "project": "oyster",
- "location": "nudibranch",
- }
- path = NetworkSecurityClient.common_location_path(**expected)
-
- # Check that the path construction is reversible.
- actual = NetworkSecurityClient.parse_common_location_path(path)
- assert expected == actual
-
-
-def test_client_with_default_client_info():
- client_info = gapic_v1.client_info.ClientInfo()
-
- with mock.patch.object(
- transports.NetworkSecurityTransport, "_prep_wrapped_messages"
- ) as prep:
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
- )
- prep.assert_called_once_with(client_info)
-
- with mock.patch.object(
- transports.NetworkSecurityTransport, "_prep_wrapped_messages"
- ) as prep:
- transport_class = NetworkSecurityClient.get_transport_class()
- transport = transport_class(
- credentials=ga_credentials.AnonymousCredentials(),
- client_info=client_info,
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
)
- prep.assert_called_once_with(client_info)
-
-
-@pytest.mark.asyncio
-async def test_transport_close_async():
- client = NetworkSecurityAsyncClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc_asyncio",
- )
- with mock.patch.object(
- type(getattr(client.transport, "grpc_channel")), "close"
- ) as close:
- async with client:
- close.assert_not_called()
- close.assert_called_once()
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
-def test_get_location_rest_bad_request(
- transport: str = "rest", request_type=locations_pb2.GetLocationRequest
-):
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ ],
+)
+def test_network_security_host_no_port(transport_name):
client = NetworkSecurityClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
+ client_options=client_options.ClientOptions(
+ api_endpoint="networksecurity.googleapis.com"
+ ),
+ transport=transport_name,
)
-
- # 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_location(request)
+ assert client.transport._host == ("networksecurity.googleapis.com:443")
@pytest.mark.parametrize(
- "request_type",
+ "transport_name",
[
- locations_pb2.GetLocationRequest,
- dict,
+ "grpc",
+ "grpc_asyncio",
],
)
-def test_get_location_rest(request_type):
+def test_network_security_host_with_port(transport_name):
client = NetworkSecurityClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ client_options=client_options.ClientOptions(
+ api_endpoint="networksecurity.googleapis.com:8000"
+ ),
+ transport=transport_name,
)
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.Location()
+ assert client.transport._host == ("networksecurity.googleapis.com:8000")
- # 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
+def test_network_security_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
- response = client.get_location(request)
+ # Check that channel is used if provided.
+ transport = transports.NetworkSecurityGrpcTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.Location)
+def test_network_security_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
-def test_list_locations_rest_bad_request(
- transport: str = "rest", request_type=locations_pb2.ListLocationsRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ # Check that channel is used if provided.
+ transport = transports.NetworkSecurityGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ channel=channel,
)
-
- request = request_type()
- request = json_format.ParseDict({"name": "projects/sample1"}, request)
-
- # 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_locations(request)
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
- "request_type",
+ "transport_class",
[
- locations_pb2.ListLocationsRequest,
- dict,
+ transports.NetworkSecurityGrpcTransport,
+ transports.NetworkSecurityGrpcAsyncIOTransport,
],
)
-def test_list_locations_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request_init = {"name": "projects/sample1"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = locations_pb2.ListLocationsResponse()
-
- # 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.list_locations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, locations_pb2.ListLocationsResponse)
-
-
-def test_get_iam_policy_rest_bad_request(
- transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest
+def test_network_security_transport_channel_mtls_with_client_cert_source(
+ transport_class,
):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
- request = request_type()
- request = json_format.ParseDict(
- {
- "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- },
- request,
- )
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.get_iam_policy(request)
+ cred = ga_credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
- "request_type",
+ "transport_class",
[
- iam_policy_pb2.GetIamPolicyRequest,
- dict,
+ transports.NetworkSecurityGrpcTransport,
+ transports.NetworkSecurityGrpcAsyncIOTransport,
],
)
-def test_get_iam_policy_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request_init = {
- "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- }
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = policy_pb2.Policy()
-
- # 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
+def test_network_security_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
- response = client.get_iam_policy(request)
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
- # Establish that the response is the type that we expect.
- assert isinstance(response, policy_pb2.Policy)
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
-def test_set_iam_policy_rest_bad_request(
- transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest
-):
+def test_network_security_grpc_lro_client():
client = NetworkSecurityClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+ transport="grpc",
)
+ transport = client.transport
- request = request_type()
- request = json_format.ParseDict(
- {
- "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- },
- request,
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.OperationsClient,
)
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.set_iam_policy(request)
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
-@pytest.mark.parametrize(
- "request_type",
- [
- iam_policy_pb2.SetIamPolicyRequest,
- dict,
- ],
-)
-def test_set_iam_policy_rest(request_type):
- client = NetworkSecurityClient(
+def test_network_security_grpc_lro_async_client():
+ client = NetworkSecurityAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport="grpc_asyncio",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.OperationsAsyncClient,
)
- request_init = {
- "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- }
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = policy_pb2.Policy()
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = json_format.MessageToJson(return_value)
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- response = client.set_iam_policy(request)
+def test_authorization_policy_path():
+ project = "squid"
+ location = "clam"
+ authorization_policy = "whelk"
+ expected = "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format(
+ project=project,
+ location=location,
+ authorization_policy=authorization_policy,
+ )
+ actual = NetworkSecurityClient.authorization_policy_path(
+ project, location, authorization_policy
+ )
+ assert expected == actual
- # Establish that the response is the type that we expect.
- assert isinstance(response, policy_pb2.Policy)
+
+def test_parse_authorization_policy_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "authorization_policy": "nudibranch",
+ }
+ path = NetworkSecurityClient.authorization_policy_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = NetworkSecurityClient.parse_authorization_policy_path(path)
+ assert expected == actual
-def test_test_iam_permissions_rest_bad_request(
- transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+def test_client_tls_policy_path():
+ project = "cuttlefish"
+ location = "mussel"
+ client_tls_policy = "winkle"
+ expected = "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(
+ project=project,
+ location=location,
+ client_tls_policy=client_tls_policy,
)
-
- request = request_type()
- request = json_format.ParseDict(
- {
- "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
- },
- request,
+ actual = NetworkSecurityClient.client_tls_policy_path(
+ project, location, client_tls_policy
)
-
- # Mock the http request call within the method and fake a BadRequest error.
- with mock.patch.object(Session, "request") as req, pytest.raises(
- core_exceptions.BadRequest
- ):
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 400
- response_value.request = Request()
- req.return_value = response_value
- client.test_iam_permissions(request)
+ assert expected == actual
-@pytest.mark.parametrize(
- "request_type",
- [
- iam_policy_pb2.TestIamPermissionsRequest,
- dict,
- ],
-)
-def test_test_iam_permissions_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request_init = {
- "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3"
+def test_parse_client_tls_policy_path():
+ expected = {
+ "project": "nautilus",
+ "location": "scallop",
+ "client_tls_policy": "abalone",
}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = iam_policy_pb2.TestIamPermissionsResponse()
-
- # 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.test_iam_permissions(request)
+ path = NetworkSecurityClient.client_tls_policy_path(**expected)
- # Establish that the response is the type that we expect.
- assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse)
+ # Check that the path construction is reversible.
+ actual = NetworkSecurityClient.parse_client_tls_policy_path(path)
+ assert expected == actual
-def test_cancel_operation_rest_bad_request(
- transport: str = "rest", request_type=operations_pb2.CancelOperationRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+def test_server_tls_policy_path():
+ project = "squid"
+ location = "clam"
+ server_tls_policy = "whelk"
+ expected = "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format(
+ project=project,
+ location=location,
+ server_tls_policy=server_tls_policy,
)
-
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2/operations/sample3"}, request
+ actual = NetworkSecurityClient.server_tls_policy_path(
+ project, location, server_tls_policy
)
+ assert expected == actual
- # 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.cancel_operation(request)
+def test_parse_server_tls_policy_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "server_tls_policy": "nudibranch",
+ }
+ path = NetworkSecurityClient.server_tls_policy_path(**expected)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.CancelOperationRequest,
- dict,
- ],
-)
-def test_cancel_operation_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
+ # Check that the path construction is reversible.
+ actual = NetworkSecurityClient.parse_server_tls_policy_path(path)
+ assert expected == actual
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
+def test_common_billing_account_path():
+ billing_account = "cuttlefish"
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = NetworkSecurityClient.common_billing_account_path(billing_account)
+ assert expected == actual
- response = client.cancel_operation(request)
- # Establish that the response is the type that we expect.
- assert response is None
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "mussel",
+ }
+ path = NetworkSecurityClient.common_billing_account_path(**expected)
+ # Check that the path construction is reversible.
+ actual = NetworkSecurityClient.parse_common_billing_account_path(path)
+ assert expected == actual
-def test_delete_operation_rest_bad_request(
- transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2/operations/sample3"}, request
+def test_common_folder_path():
+ folder = "winkle"
+ expected = "folders/{folder}".format(
+ folder=folder,
)
+ actual = NetworkSecurityClient.common_folder_path(folder)
+ assert expected == actual
- # 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_operation(request)
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "nautilus",
+ }
+ path = NetworkSecurityClient.common_folder_path(**expected)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.DeleteOperationRequest,
- dict,
- ],
-)
-def test_delete_operation_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = None
+ # Check that the path construction is reversible.
+ actual = NetworkSecurityClient.parse_common_folder_path(path)
+ assert expected == actual
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- json_return_value = "{}"
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
+def test_common_organization_path():
+ organization = "scallop"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = NetworkSecurityClient.common_organization_path(organization)
+ assert expected == actual
- response = client.delete_operation(request)
- # Establish that the response is the type that we expect.
- assert response is None
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "abalone",
+ }
+ path = NetworkSecurityClient.common_organization_path(**expected)
+ # Check that the path construction is reversible.
+ actual = NetworkSecurityClient.parse_common_organization_path(path)
+ assert expected == actual
-def test_get_operation_rest_bad_request(
- transport: str = "rest", request_type=operations_pb2.GetOperationRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2/operations/sample3"}, request
+def test_common_project_path():
+ project = "squid"
+ expected = "projects/{project}".format(
+ project=project,
)
+ actual = NetworkSecurityClient.common_project_path(project)
+ assert expected == actual
- # 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_operation(request)
+def test_parse_common_project_path():
+ expected = {
+ "project": "clam",
+ }
+ path = NetworkSecurityClient.common_project_path(**expected)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.GetOperationRequest,
- dict,
- ],
-)
-def test_get_operation_rest(request_type):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation()
+ # Check that the path construction is reversible.
+ actual = NetworkSecurityClient.parse_common_project_path(path)
+ assert expected == actual
- # 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
+def test_common_location_path():
+ project = "whelk"
+ location = "octopus"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = NetworkSecurityClient.common_location_path(project, location)
+ assert expected == actual
- response = client.get_operation(request)
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.Operation)
+def test_parse_common_location_path():
+ expected = {
+ "project": "oyster",
+ "location": "nudibranch",
+ }
+ path = NetworkSecurityClient.common_location_path(**expected)
+ # Check that the path construction is reversible.
+ actual = NetworkSecurityClient.parse_common_location_path(path)
+ assert expected == actual
-def test_list_operations_rest_bad_request(
- transport: str = "rest", request_type=operations_pb2.ListOperationsRequest
-):
- client = NetworkSecurityClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
- request = request_type()
- request = json_format.ParseDict(
- {"name": "projects/sample1/locations/sample2"}, request
- )
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
- # 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_operations(request)
+ with mock.patch.object(
+ transports.NetworkSecurityTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = NetworkSecurityClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.NetworkSecurityTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = NetworkSecurityClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
-@pytest.mark.parametrize(
- "request_type",
- [
- operations_pb2.ListOperationsRequest,
- dict,
- ],
-)
-def test_list_operations_rest(request_type):
- client = NetworkSecurityClient(
+@pytest.mark.asyncio
+async def test_transport_close_async():
+ client = NetworkSecurityAsyncClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport="grpc_asyncio",
)
- request_init = {"name": "projects/sample1/locations/sample2"}
- request = request_type(**request_init)
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(type(client.transport._session), "request") as req:
- # Designate an appropriate value for the returned response.
- return_value = operations_pb2.ListOperationsResponse()
-
- # 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.list_operations(request)
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, operations_pb2.ListOperationsResponse)
+ with mock.patch.object(
+ type(getattr(client.transport, "grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
def test_delete_operation(transport: str = "grpc"):
@@ -12577,7 +7232,6 @@ async def test_test_iam_permissions_from_dict_async():
def test_transport_close():
transports = {
- "rest": "_session",
"grpc": "_grpc_channel",
}
@@ -12595,7 +7249,6 @@ def test_transport_close():
def test_client_ctx():
transports = [
- "rest",
"grpc",
]
for transport in transports:
From 0c33ec96722d2222a38c916632f6e3fb46383166 Mon Sep 17 00:00:00 2001
From: "release-please[bot]"
<55107282+release-please[bot]@users.noreply.github.com>
Date: Wed, 11 Jan 2023 11:01:11 -0500
Subject: [PATCH 3/3] chore(main): release 0.9.0 (#157)
* chore(main): release 0.9.0
* add classifier for python 3.11
Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com>
Co-authored-by: Anthonios Partheniou
---
.release-please-manifest.json | 2 +-
CHANGELOG.md | 7 +++++++
google/cloud/network_security/gapic_version.py | 2 +-
google/cloud/network_security_v1/gapic_version.py | 2 +-
google/cloud/network_security_v1beta1/gapic_version.py | 2 +-
.../snippet_metadata_google.cloud.networksecurity.v1.json | 2 +-
...ppet_metadata_google.cloud.networksecurity.v1beta1.json | 2 +-
setup.py | 2 ++
8 files changed, 15 insertions(+), 6 deletions(-)
diff --git a/.release-please-manifest.json b/.release-please-manifest.json
index 64f3cdd..76d5538 100644
--- a/.release-please-manifest.json
+++ b/.release-please-manifest.json
@@ -1,3 +1,3 @@
{
- ".": "0.8.0"
+ ".": "0.9.0"
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4bfeaea..b255230 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
# Changelog
+## [0.9.0](https://github.com/googleapis/python-network-security/compare/v0.8.0...v0.9.0) (2023-01-10)
+
+
+### Features
+
+* Add support for python 3.11 ([#156](https://github.com/googleapis/python-network-security/issues/156)) ([5233d61](https://github.com/googleapis/python-network-security/commit/5233d61f1c31da18125844e8059e7bb8e157150c))
+
## [0.8.0](https://github.com/googleapis/python-network-security/compare/v0.7.2...v0.8.0) (2022-12-14)
diff --git a/google/cloud/network_security/gapic_version.py b/google/cloud/network_security/gapic_version.py
index b88d7a7..8e0b747 100644
--- a/google/cloud/network_security/gapic_version.py
+++ b/google/cloud/network_security/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "0.8.0" # {x-release-please-version}
+__version__ = "0.9.0" # {x-release-please-version}
diff --git a/google/cloud/network_security_v1/gapic_version.py b/google/cloud/network_security_v1/gapic_version.py
index b88d7a7..8e0b747 100644
--- a/google/cloud/network_security_v1/gapic_version.py
+++ b/google/cloud/network_security_v1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "0.8.0" # {x-release-please-version}
+__version__ = "0.9.0" # {x-release-please-version}
diff --git a/google/cloud/network_security_v1beta1/gapic_version.py b/google/cloud/network_security_v1beta1/gapic_version.py
index b88d7a7..8e0b747 100644
--- a/google/cloud/network_security_v1beta1/gapic_version.py
+++ b/google/cloud/network_security_v1beta1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "0.8.0" # {x-release-please-version}
+__version__ = "0.9.0" # {x-release-please-version}
diff --git a/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json
index 0bc5339..7b5d363 100644
--- a/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json
+++ b/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-network-security",
- "version": "0.1.0"
+ "version": "0.9.0"
},
"snippets": [
{
diff --git a/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json
index fd7e421..ced2a90 100644
--- a/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json
+++ b/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-network-security",
- "version": "0.1.0"
+ "version": "0.9.0"
},
"snippets": [
{
diff --git a/setup.py b/setup.py
index 0242d7b..34b5dcd 100644
--- a/setup.py
+++ b/setup.py
@@ -40,6 +40,7 @@
dependencies = [
"google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*",
"proto-plus >= 1.22.0, <2.0.0dev",
+ "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'",
"protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5",
"grpc-google-iam-v1 >=0.12.4, <1.0.0dev",
]
@@ -80,6 +81,7 @@
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
"Operating System :: OS Independent",
"Topic :: Internet",
],